<commit_before>AliAnalysisTaskNewJetSubstructure* AddTaskNewJetSubstructure(const char * njetsBase,
                                                     const char * njetsUS,
						     const char * njetsTrue,
                                                     const char * njetsPartLevel,
						     const Double_t R,
						     const char * nrhoBase,
						     const char * ntracks,
                                                     const char * ntracksUS,
                                                     const char *ntracksPartLevel,
						     const char * nclusters,
						     const char * ntracksTrue,
						     const char *type,
						     const char *CentEst,
						     Int_t       pSel,
						     TString     trigClass      = "",
						     TString     kEmcalTriggers = "",
						     TString     tag            = "",
						     AliAnalysisTaskNewJetSubstructure::JetShapeType jetShapeType = AliAnalysisTaskNewJetSubstructure::kMCTrue,
						     AliAnalysisTaskNewJetSubstructure::JetShapeSub jetShapeSub = AliAnalysisTaskNewJetSubstructure::kNoSub,
						     AliAnalysisTaskNewJetSubstructure::JetSelectionType jetSelection = AliAnalysisTaskNewJetSubstructure::kInclusive,
						     Float_t minpTHTrigger =0.,  Float_t maxpTHTrigger =0., Float_t acut =0.6, AliAnalysisTaskNewJetSubstructure::DerivSubtrOrder derivSubtrOrder = AliAnalysisTaskNewJetSubstructure::kSecondOrder ) {

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
    {
      Error("AddTaskNewJetSubstructure","No analysis manager found.");
      return 0;
    }
  Bool_t ismc=kFALSE;
  ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
    {
      ::Error("AddTaskNewJetSubstructure", "This task requires an input event handler");
      return NULL;
    }

  TString wagonName1 = Form("JetSubstructure_%s_TC%s%s",njetsBase,trigClass.Data(),tag.Data());
  TString wagonName2 = Form("JetSubstructure_%s_TC%s%sTree",njetsBase,trigClass.Data(),tag.Data());
  //Configure jet tagger task
  AliAnalysisTaskNewJetSubstructure *task = new AliAnalysisTaskNewJetSubstructure(wagonName1.Data());

  //task->SetNCentBins(4);
  task->SetJetShapeType(jetShapeType);
  task->SetJetShapeSub(jetShapeSub);
  task->SetJetSelection(jetSelection);
  task->SetDerivativeSubtractionOrder(derivSubtrOrder);

  TString thename(njetsBase);
  //if(thename.Contains("Sub")) task->SetIsConstSub(kTRUE);
  //task->SetVzRange(-10.,10.);

  AliParticleContainer *trackCont;// = task->AddTrackContainer(ntracks);

  if ((jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) && ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kData) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef))){
    trackCont = task->AddParticleContainer(ntracks);}
  else trackCont = task->AddTrackContainer(ntracks);

  //Printf("tracks() = %s, trackCont =%p", ntracks, trackCont);
  AliParticleContainer *trackContUS  = task->AddTrackContainer(ntracksUS);
  //Printf("tracksUS() = %s", ntracksUS);
  AliParticleContainer *trackContTrue = task->AddMCParticleContainer(ntracksTrue);
  //Printf("ntracksTrue() = %s, trackContTrue=%p ", ntracksTrue, trackContTrue);
   if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) trackContTrue->SetIsEmbedding(true);
  AliParticleContainer *trackContPartLevel=0;

  if ((jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) && ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kMCTrue) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef))){
    trackContPartLevel = task->AddParticleContainer(ntracksPartLevel);
  }
  else trackContPartLevel = task->AddMCParticleContainer(ntracksPartLevel);
    if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) trackContPartLevel->SetIsEmbedding(true);
   //Printf("ntracksPartLevel() = %s, trackContPartLevel=%p ", ntracksPartLevel, trackContPartLevel);

  AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);

  AliJetContainer *jetContBase=0x0;
  AliJetContainer *jetContUS=0x0;
  AliJetContainer *jetContTrue=0x0;
  AliJetContainer *jetContPart=0x0;
  TString strType(type);

  if ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kMCTrue || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kGenOnTheFly))) {
    jetContBase = task->AddJetContainer(njetsBase,strType,R);
    if(jetContBase) {
      jetContBase->SetRhoName(nrhoBase);
      jetContBase->ConnectParticleContainer(trackContPartLevel);
      jetContBase->ConnectClusterContainer(clusterCont);
      jetContBase->SetPercAreaCut(acut);
    }
  }

  if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kData){
    jetContBase = task->AddJetContainer(njetsBase,strType,R);
    if(jetContBase) {
      jetContBase->SetRhoName(nrhoBase);
      jetContBase->ConnectParticleContainer(trackCont);
      jetContBase->ConnectClusterContainer(clusterCont);
      jetContBase->SetPercAreaCut(acut);
      if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) jetContBase->SetAreaEmcCut(-2);
    }
  }

  if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia){
    jetContBase = task->AddJetContainer(njetsBase,strType,R);
    if(jetContBase) {
      jetContBase->SetRhoName(nrhoBase);
      jetContBase->ConnectParticleContainer(trackCont);
      jetContBase->ConnectClusterContainer(clusterCont);
      jetContBase->SetPercAreaCut(acut);

      if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) jetContBase->SetAreaEmcCut(-2);
    }

    jetContTrue = task->AddJetContainer(njetsTrue,strType,R);
    if(jetContTrue) {

      jetContTrue->SetRhoName(nrhoBase);
      jetContTrue->ConnectParticleContainer(trackContTrue);
      jetContTrue->SetPercAreaCut(acut);

    }

    if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub || jetShapeSub==AliAnalysisTaskNewJetSubstructure::kEventSub){
      jetContUS=task->AddJetContainer(njetsUS,strType,R);
      if(jetContUS) {
        jetContUS->SetRhoName(nrhoBase);
        jetContUS->ConnectParticleContainer(trackContUS);
        jetContUS->SetPercAreaCut(acut);

      }
    }

     jetContPart = task->AddJetContainer(njetsPartLevel,strType,R);
      if(jetContPart) {

        jetContPart->SetRhoName(nrhoBase);
        jetContPart->ConnectParticleContainer(trackContPartLevel);
        jetContPart->SetPercAreaCut(acut);

      }
  }

  if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef){

    jetContBase = task->AddJetContainer(njetsBase,strType,R);
    if(jetContBase) {
      jetContBase->ConnectParticleContainer(trackCont);
      jetContBase->ConnectClusterContainer(clusterCont);
      jetContBase->SetPercAreaCut(acut);
    }

    jetContTrue = task->AddJetContainer(njetsTrue,strType,R);
    if(jetContTrue) {
      jetContTrue->SetRhoName(nrhoBase);
      jetContTrue->ConnectParticleContainer(trackContTrue);
      jetContTrue->SetPercAreaCut(acut);

    }

    if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub){
      jetContUS=task->AddJetContainer(njetsUS,strType,R);
      if(jetContUS) {
        jetContUS->SetRhoName(nrhoBase);
        jetContUS->ConnectParticleContainer(trackContUS);
        jetContUS->SetPercAreaCut(acut);

      }
    }

    jetContPart = task->AddJetContainer(njetsPartLevel,strType,R);
    if(jetContPart) {
      jetContPart->SetRhoName(nrhoBase);
      jetContPart->ConnectParticleContainer(trackContPartLevel);
      jetContPart->SetPercAreaCut(acut);
    }

  }

  task->SetCaloTriggerPatchInfoName(kEmcalTriggers.Data());
  task->SetCentralityEstimator(CentEst);
  task->SelectCollisionCandidates(pSel);
  task->SetUseAliAnaUtils(kFALSE);

  mgr->AddTask(task);

  //Connnect input
  mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() );

  //Connect output
  TString contName1(wagonName1);
  TString contName2(wagonName2);

  if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kMCTrue) contName1 += "_MCTrue";
  if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kData) contName1 += "_Data";

  if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kPythiaDef) contName1 +="_PythiaDef";
  if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kNoSub) contName1 += "_NoSub";
  if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kConstSub) contName1 += "_ConstSub";
   if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kEventSub) contName1 += "_EventSub";
  if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kDerivSub) contName1 += "_DerivSub";

  if (jetSelection == AliAnalysisTaskNewJetSubstructure::kInclusive) contName1 += "_Incl";

    if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kMCTrue) contName2 += "_MCTrue";
  if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kData) contName2 += "_Data";

  if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kPythiaDef) contName2 +="_PythiaDef";
  if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kNoSub) contName2 += "_NoSub";
  if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kConstSub) contName2 += "_ConstSub";
  if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kEventSub) contName2 += "_EventSub";
  if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kDerivSub) contName2 += "_DerivSub";

  if (jetSelection == AliAnalysisTaskNewJetSubstructure::kInclusive) contName2 += "_Incl";

  TString outputfile = Form("%s",AliAnalysisManager::GetCommonFileName());
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName1.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile);
   mgr->ConnectOutput(task,1,coutput1);

   AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(contName2.Data(), TTree::Class(),AliAnalysisManager::kOutputContainer,outputfile);
  mgr->ConnectOutput(task,2,coutput2);

  return task;

}

<commit_msg>one extra piece I forgot now it should work<commit_after>AliAnalysisTaskNewJetSubstructure* AddTaskNewJetSubstructure(const char * njetsBase,
                                                     const char * njetsUS,
						     const char * njetsTrue,
                                                     const char * njetsPartLevel,
						     const Double_t R,
						     const char * nrhoBase,
						     const char * ntracks,
                                                     const char * ntracksUS,
                                                     const char *ntracksPartLevel,
						     const char * nclusters,
						     const char * ntracksTrue,
						     const char *type,
						     const char *CentEst,
						     Int_t       pSel,
						     TString     trigClass      = "",
						     TString     kEmcalTriggers = "",
						     TString     tag            = "",
						     AliAnalysisTaskNewJetSubstructure::JetShapeType jetShapeType = AliAnalysisTaskNewJetSubstructure::kMCTrue,
						     AliAnalysisTaskNewJetSubstructure::JetShapeSub jetShapeSub = AliAnalysisTaskNewJetSubstructure::kNoSub,
						     AliAnalysisTaskNewJetSubstructure::JetSelectionType jetSelection = AliAnalysisTaskNewJetSubstructure::kInclusive,
						     Float_t minpTHTrigger =0.,  Float_t maxpTHTrigger =0., Float_t acut =0.6, AliAnalysisTaskNewJetSubstructure::DerivSubtrOrder derivSubtrOrder = AliAnalysisTaskNewJetSubstructure::kSecondOrder ) {

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
    {
      Error("AddTaskNewJetSubstructure","No analysis manager found.");
      return 0;
    }
  Bool_t ismc=kFALSE;
  ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler())
    {
      ::Error("AddTaskNewJetSubstructure", "This task requires an input event handler");
      return NULL;
    }

  TString wagonName1 = Form("JetSubstructure_%s_TC%s%s",njetsBase,trigClass.Data(),tag.Data());
  TString wagonName2 = Form("JetSubstructure_%s_TC%s%sTree",njetsBase,trigClass.Data(),tag.Data());
  //Configure jet tagger task
  AliAnalysisTaskNewJetSubstructure *task = new AliAnalysisTaskNewJetSubstructure(wagonName1.Data());

  //task->SetNCentBins(4);
  task->SetJetShapeType(jetShapeType);
  task->SetJetShapeSub(jetShapeSub);
  task->SetJetSelection(jetSelection);
  task->SetDerivativeSubtractionOrder(derivSubtrOrder);

  TString thename(njetsBase);
  //if(thename.Contains("Sub")) task->SetIsConstSub(kTRUE);
  //task->SetVzRange(-10.,10.);

  AliParticleContainer *trackCont;// = task->AddTrackContainer(ntracks);

  if ((jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub || jetShapeSub==AliAnalysisTaskNewJetSubstructure::kEventSub ) && ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kData) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef))){
    trackCont = task->AddParticleContainer(ntracks);}
  else trackCont = task->AddTrackContainer(ntracks);

  //Printf("tracks() = %s, trackCont =%p", ntracks, trackCont);
  AliParticleContainer *trackContUS  = task->AddTrackContainer(ntracksUS);
  //Printf("tracksUS() = %s", ntracksUS);
  AliParticleContainer *trackContTrue = task->AddMCParticleContainer(ntracksTrue);
  //Printf("ntracksTrue() = %s, trackContTrue=%p ", ntracksTrue, trackContTrue);
   if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) trackContTrue->SetIsEmbedding(true);
  AliParticleContainer *trackContPartLevel=0;

  if ((jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) && ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kMCTrue) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef))){
    trackContPartLevel = task->AddParticleContainer(ntracksPartLevel);
  }
  else trackContPartLevel = task->AddMCParticleContainer(ntracksPartLevel);
    if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) trackContPartLevel->SetIsEmbedding(true);
   //Printf("ntracksPartLevel() = %s, trackContPartLevel=%p ", ntracksPartLevel, trackContPartLevel);

  AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);

  AliJetContainer *jetContBase=0x0;
  AliJetContainer *jetContUS=0x0;
  AliJetContainer *jetContTrue=0x0;
  AliJetContainer *jetContPart=0x0;
  TString strType(type);

  if ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kMCTrue || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kGenOnTheFly))) {
    jetContBase = task->AddJetContainer(njetsBase,strType,R);
    if(jetContBase) {
      jetContBase->SetRhoName(nrhoBase);
      jetContBase->ConnectParticleContainer(trackContPartLevel);
      jetContBase->ConnectClusterContainer(clusterCont);
      jetContBase->SetPercAreaCut(acut);
    }
  }

  if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kData){
    jetContBase = task->AddJetContainer(njetsBase,strType,R);
    if(jetContBase) {
      jetContBase->SetRhoName(nrhoBase);
      jetContBase->ConnectParticleContainer(trackCont);
      jetContBase->ConnectClusterContainer(clusterCont);
      jetContBase->SetPercAreaCut(acut);
      if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) jetContBase->SetAreaEmcCut(-2);
    }
  }

  if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia){
    jetContBase = task->AddJetContainer(njetsBase,strType,R);
    if(jetContBase) {
      jetContBase->SetRhoName(nrhoBase);
      jetContBase->ConnectParticleContainer(trackCont);
      jetContBase->ConnectClusterContainer(clusterCont);
      jetContBase->SetPercAreaCut(acut);

      if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) jetContBase->SetAreaEmcCut(-2);
    }

    jetContTrue = task->AddJetContainer(njetsTrue,strType,R);
    if(jetContTrue) {

      jetContTrue->SetRhoName(nrhoBase);
      jetContTrue->ConnectParticleContainer(trackContTrue);
      jetContTrue->SetPercAreaCut(acut);

    }

    if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub || jetShapeSub==AliAnalysisTaskNewJetSubstructure::kEventSub){
      jetContUS=task->AddJetContainer(njetsUS,strType,R);
      if(jetContUS) {
        jetContUS->SetRhoName(nrhoBase);
        jetContUS->ConnectParticleContainer(trackContUS);
        jetContUS->SetPercAreaCut(acut);

      }
    }

     jetContPart = task->AddJetContainer(njetsPartLevel,strType,R);
      if(jetContPart) {

        jetContPart->SetRhoName(nrhoBase);
        jetContPart->ConnectParticleContainer(trackContPartLevel);
        jetContPart->SetPercAreaCut(acut);

      }
  }

  if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef){

    jetContBase = task->AddJetContainer(njetsBase,strType,R);
    if(jetContBase) {
      jetContBase->ConnectParticleContainer(trackCont);
      jetContBase->ConnectClusterContainer(clusterCont);
      jetContBase->SetPercAreaCut(acut);
    }

    jetContTrue = task->AddJetContainer(njetsTrue,strType,R);
    if(jetContTrue) {
      jetContTrue->SetRhoName(nrhoBase);
      jetContTrue->ConnectParticleContainer(trackContTrue);
      jetContTrue->SetPercAreaCut(acut);

    }

    if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub){
      jetContUS=task->AddJetContainer(njetsUS,strType,R);
      if(jetContUS) {
        jetContUS->SetRhoName(nrhoBase);
        jetContUS->ConnectParticleContainer(trackContUS);
        jetContUS->SetPercAreaCut(acut);

      }
    }

    jetContPart = task->AddJetContainer(njetsPartLevel,strType,R);
    if(jetContPart) {
      jetContPart->SetRhoName(nrhoBase);
      jetContPart->ConnectParticleContainer(trackContPartLevel);
      jetContPart->SetPercAreaCut(acut);
    }

  }

  task->SetCaloTriggerPatchInfoName(kEmcalTriggers.Data());
  task->SetCentralityEstimator(CentEst);
  task->SelectCollisionCandidates(pSel);
  task->SetUseAliAnaUtils(kFALSE);

  mgr->AddTask(task);

  //Connnect input
  mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() );

  //Connect output
  TString contName1(wagonName1);
  TString contName2(wagonName2);

  if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kMCTrue) contName1 += "_MCTrue";
  if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kData) contName1 += "_Data";

  if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kPythiaDef) contName1 +="_PythiaDef";
  if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kNoSub) contName1 += "_NoSub";
  if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kConstSub) contName1 += "_ConstSub";
   if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kEventSub) contName1 += "_EventSub";
  if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kDerivSub) contName1 += "_DerivSub";

  if (jetSelection == AliAnalysisTaskNewJetSubstructure::kInclusive) contName1 += "_Incl";

    if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kMCTrue) contName2 += "_MCTrue";
  if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kData) contName2 += "_Data";

  if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kPythiaDef) contName2 +="_PythiaDef";
  if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kNoSub) contName2 += "_NoSub";
  if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kConstSub) contName2 += "_ConstSub";
  if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kEventSub) contName2 += "_EventSub";
  if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kDerivSub) contName2 += "_DerivSub";

  if (jetSelection == AliAnalysisTaskNewJetSubstructure::kInclusive) contName2 += "_Incl";

  TString outputfile = Form("%s",AliAnalysisManager::GetCommonFileName());
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName1.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile);
   mgr->ConnectOutput(task,1,coutput1);

   AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(contName2.Data(), TTree::Class(),AliAnalysisManager::kOutputContainer,outputfile);
  mgr->ConnectOutput(task,2,coutput2);

  return task;

}

<|endoftext|>


<commit_before><commit_msg>added assertion on minzPtr<commit_after><|endoftext|>


<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2016 Intel Corporation. All Rights Reserved.

#include "ds5-options.h"

namespace rsimpl2
{
    const char* emitter_option::get_value_description(float val) const
    {
        switch (static_cast<int>(val))
        {
            case 0:
            {
                return "Off";
            }
            case 1:
            {
                return "On";
            }
            case 2:
            {
                return "Auto";
            }
            default:
                throw invalid_value_exception("value not found");
        }
    }

    emitter_option::emitter_option(uvc_endpoint& ep)
        : uvc_xu_option(ep, ds::depth_xu, ds::DS5_DEPTH_EMITTER_ENABLED,
                        "Power of the DS5 projector, 0 meaning projector off, 1 meaning projector on, 2 meaning projector in auto mode")
    {}

    float asic_and_projector_temperature_options::query() const
    {
        if (!is_enabled())
            throw wrong_api_call_sequence_exception("query option is allow only in streaming!");

        #pragma pack(push, 1)
        struct temperature
        {
            uint8_t is_projector_valid;
            uint8_t is_asic_valid;
            int8_t projector_temperature;
            int8_t asic_temperature;
        };
        #pragma pack(pop)

        auto temperature_data = static_cast<temperature>(_ep.invoke_powered(
            [this](uvc::uvc_device& dev)
            {
                temperature temp{};
                if (!dev.get_xu(ds::depth_xu,
                                ds::DS5_ASIC_AND_PROJECTOR_TEMPERATURES,
                                reinterpret_cast<uint8_t*>(&temp),
                                sizeof(temperature)))
                 {
                        throw invalid_value_exception(to_string() << "get_xu(ctrl=DS5_ASIC_AND_PROJECTOR_TEMPERATURES) failed!" << " Last Error: " << strerror(errno));
                 }

                return temp;
            }));

        int8_t temperature::* feild;
        uint8_t temperature::* is_valid_feild;

        switch (_option)
        {
        case RS2_OPTION_ASIC_TEMPERATURE:
            feild = &temperature::asic_temperature;
            is_valid_feild = &temperature::is_asic_valid;
            break;
        case RS2_OPTION_PROJECTOR_TEMPERATURE:
            feild = &temperature::projector_temperature;
            is_valid_feild = &temperature::is_projector_valid;
            break;
        default:
            throw invalid_value_exception(to_string() << rs2_option_to_string(_option) << " is not temperature option!");
        }

        if (!static_cast<bool>(temperature_data.*is_valid_feild))
            throw invalid_value_exception(to_string() << rs2_option_to_string(_option) << " value is not valid!");

        return temperature_data.*feild;
    }

    option_range asic_and_projector_temperature_options::get_range() const
    {
        return option_range { -40, 125, 0, 0 };
    }

    bool asic_and_projector_temperature_options::is_enabled() const
    {
        return _ep.is_streaming();
    }

    const char* asic_and_projector_temperature_options::get_description() const
    {
        switch (_option)
        {
        case RS2_OPTION_ASIC_TEMPERATURE:
            return "Current Asic Temperature";
        case RS2_OPTION_PROJECTOR_TEMPERATURE:
            return "Current Projector Temperature";
        default:
            throw invalid_value_exception(to_string() << rs2_option_to_string(_option) << " is not temperature option!");
        }
    }

    asic_and_projector_temperature_options::asic_and_projector_temperature_options(uvc_endpoint& ep, rs2_option opt)
        : _option(opt), _ep(ep)
        {}

    float motion_module_temperature_option::query() const
    {
        if (!is_enabled())
            throw wrong_api_call_sequence_exception("query option is allow only in streaming!");

        static const auto report_field = uvc::custom_sensor_report_field::value;
        auto data = _ep.get_custom_report_data(custom_sensor_name, report_name, report_field);
        if (data.empty())
            throw invalid_value_exception("query() motion_module_temperature_option failed! Empty buffer arrived.");

        auto data_str = std::string(reinterpret_cast<char const*>(data.data()));
        return std::stof(data_str);
    }

    option_range motion_module_temperature_option::get_range() const
    {
        if (!is_enabled())
            throw wrong_api_call_sequence_exception("get option range is allow only in streaming!");

        static const auto min_report_field = uvc::custom_sensor_report_field::minimum;
        static const auto max_report_field = uvc::custom_sensor_report_field::maximum;
        auto min_data = _ep.get_custom_report_data(custom_sensor_name, report_name, min_report_field);
        if (min_data.empty())
            throw invalid_value_exception("get_range() motion_module_temperature_option failed! Empty buffer arrived.");

        auto max_data = _ep.get_custom_report_data(custom_sensor_name, report_name, max_report_field);
        if (max_data.empty())
            throw invalid_value_exception("get_range() motion_module_temperature_option failed! Empty buffer arrived.");

        auto min_str = std::string(reinterpret_cast<char const*>(min_data.data()));
        auto max_str = std::string(reinterpret_cast<char const*>(max_data.data()));

        return option_range{std::stof(min_str),
                            std::stof(max_str),
                            0, 0};
    }

    bool motion_module_temperature_option::is_enabled() const
    {
        return _ep.is_streaming();
    }

    const char* motion_module_temperature_option::get_description() const
    {
        return "Current Motion-Module Temperature";
    }

    motion_module_temperature_option::motion_module_temperature_option(hid_endpoint& ep)
        : _ep(ep)
    {}

    void enable_motion_correction::set(float value)
    {
        _is_enabled = value > 0;
    }

    float enable_motion_correction::query() const
    {
        auto is_enabled = _is_enabled.load();
        return is_enabled ? 1.f : 0.f;
    }

    enable_motion_correction::enable_motion_correction(endpoint* mm_ep,
                                                       ds::imu_intrinsics accel,
                                                       ds::imu_intrinsics gyro)
        : _is_enabled(true), _accel(accel), _gyro(gyro)
    {
        mm_ep->register_on_before_frame_callback(
                    [this](rs2_stream stream, rs2_frame& f, callback_invocation_holder callback)
        {
            auto fr = f.get();
            if (_is_enabled.load() && fr->get_format() == RS2_FORMAT_MOTION_XYZ32F)
            {
                auto xyz = (float*)(fr->get_frame_data());

                if (stream == RS2_STREAM_ACCEL)
                {
                    for (int i = 0; i < 3; i++)
                        xyz[i] = xyz[i] * _accel.scale[i] + _accel.bias[i];
                }

                if (stream == RS2_STREAM_GYRO)
                {
                    for (int i = 0; i < 3; i++)
                        xyz[i] = xyz[i] * _gyro.scale[i] + _gyro.bias[i];
                }
            }
        });
    }

    void enable_auto_exposure_option::set(float value)
    {
        if (value <0 ) throw invalid_value_exception("Invalid Auto-Exposure mode request " + std::to_string(value));

        auto auto_exposure_prev_state = _auto_exposure_state->get_enable_auto_exposure();
        _auto_exposure_state->set_enable_auto_exposure(0.f < std::fabs(value));

        if (_auto_exposure_state->get_enable_auto_exposure()) // auto_exposure current value
        {
            if (!auto_exposure_prev_state) // auto_exposure previous value
            {
                _to_add_frames = true; // auto_exposure moved from disable to enable
            }
        }
        else
        {
            if (auto_exposure_prev_state)
            {
                _to_add_frames = false; // auto_exposure moved from enable to disable
            }
        }
    }

    float enable_auto_exposure_option::query() const
    {
        return _auto_exposure_state->get_enable_auto_exposure();
    }

    enable_auto_exposure_option::enable_auto_exposure_option(uvc_endpoint* fisheye_ep,
                                std::shared_ptr<auto_exposure_mechanism> auto_exposure,
                                std::shared_ptr<auto_exposure_state> auto_exposure_state)
        : _auto_exposure_state(auto_exposure_state),
          _to_add_frames((_auto_exposure_state->get_enable_auto_exposure())),
          _auto_exposure(auto_exposure)
    {
        fisheye_ep->register_on_before_frame_callback(
                    [this](rs2_stream stream, rs2_frame& f, callback_invocation_holder callback)
        {
            if (!_to_add_frames || stream != RS2_STREAM_FISHEYE)
                return;

            _auto_exposure->add_frame(f.get()->get_owner()->clone_frame(&f), std::move(callback));
        });
    }

    auto_exposure_mode_option::auto_exposure_mode_option(
                              std::shared_ptr<auto_exposure_mechanism> auto_exposure,
                              std::shared_ptr<auto_exposure_state> auto_exposure_state)
        : _auto_exposure_state(auto_exposure_state),
          _auto_exposure(auto_exposure)
    {}

    void auto_exposure_mode_option::set(float value)
    {
        _auto_exposure_state->set_auto_exposure_mode(static_cast<auto_exposure_modes>((int)value));
        _auto_exposure->update_auto_exposure_state(*_auto_exposure_state);
    }

    float auto_exposure_mode_option::query() const
    {
        return static_cast<float>(_auto_exposure_state->get_auto_exposure_mode());
    }

    const char* auto_exposure_mode_option::get_value_description(float val) const
    {
        switch (static_cast<int>(val))
        {
            case 0:
            {
                return "Static";
            }
            case 1:
            {
                return "Anti-Flicker";
            }
            case 2:
            {
                return "Hybrid";
            }
            default:
                throw invalid_value_exception("value not found");
        }
    }

    auto_exposure_antiflicker_rate_option::auto_exposure_antiflicker_rate_option(
                                          std::shared_ptr<auto_exposure_mechanism> auto_exposure,
                                          std::shared_ptr<auto_exposure_state> auto_exposure_state)
        : _auto_exposure_state(auto_exposure_state),
          _auto_exposure(auto_exposure)
    {}

    void auto_exposure_antiflicker_rate_option::set(float value)
    {
        _auto_exposure_state->set_auto_exposure_antiflicker_rate(static_cast<uint32_t>(value));
        _auto_exposure->update_auto_exposure_state(*_auto_exposure_state);
    }

    float auto_exposure_antiflicker_rate_option::query() const
    {
        return static_cast<float>(_auto_exposure_state->get_auto_exposure_antiflicker_rate());
    }

    const char* auto_exposure_antiflicker_rate_option::get_value_description(float val) const
    {
        switch (static_cast<int>(val))
        {
            case 50:
            {
                return "50Hz";
            }
            case 60:
            {
                return "60Hz";
            }
            default:
                throw invalid_value_exception("antiflicker_rate: get_value_description(...) failed. value not found!");
        }
    }

    ds::depth_table_control depth_scale_option::get_depth_table(ds::advnaced_query_mode mode) const
    {
        command cmd(ds::GET_ADV);
        cmd.param1 = ds::etDepthTableControl;
        cmd.param2 = mode;
        auto res = _hwm.send(cmd);

        if (res.size() < sizeof(ds::depth_table_control))
            throw std::runtime_error("Not enough bytes returned from the firmware!");

        auto table = (const ds::depth_table_control*)res.data();
        return *table;
    }

    depth_scale_option::depth_scale_option(hw_monitor& hwm)
        : _hwm(hwm)
    {
        _range = [this]()
        {
            auto min = get_depth_table(ds::GET_MIN);
            auto max = get_depth_table(ds::GET_MAX);
            return option_range{ (float)(0.000001 * min.depth_units),
                                 (float)(0.000001 * max.depth_units),
                                 0.000001f, 0.001f };
        };
    }

    void depth_scale_option::set(float value)
    {
        command cmd(ds::SET_ADV);
        cmd.param1 = ds::etDepthTableControl;

        auto depth_table = get_depth_table(ds::GET_VAL);
        depth_table.depth_units = 1000000 * value;
        auto ptr = (uint8_t*)(&depth_table);
        cmd.data = std::vector<uint8_t>(ptr, ptr + sizeof(ds::depth_table_control));

        _hwm.send(cmd);
    }

    float depth_scale_option::query() const
    {
        auto table = get_depth_table(ds::GET_VAL);
        return (float)(0.000001 * table.depth_units);
    }

    option_range depth_scale_option::get_range() const
    {
        return *_range;
    }
}
<commit_msg>Fixed IMU intrinsics formula. Tracked On: DSO-5510<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2016 Intel Corporation. All Rights Reserved.

#include "ds5-options.h"

namespace rsimpl2
{
    const char* emitter_option::get_value_description(float val) const
    {
        switch (static_cast<int>(val))
        {
            case 0:
            {
                return "Off";
            }
            case 1:
            {
                return "On";
            }
            case 2:
            {
                return "Auto";
            }
            default:
                throw invalid_value_exception("value not found");
        }
    }

    emitter_option::emitter_option(uvc_endpoint& ep)
        : uvc_xu_option(ep, ds::depth_xu, ds::DS5_DEPTH_EMITTER_ENABLED,
                        "Power of the DS5 projector, 0 meaning projector off, 1 meaning projector on, 2 meaning projector in auto mode")
    {}

    float asic_and_projector_temperature_options::query() const
    {
        if (!is_enabled())
            throw wrong_api_call_sequence_exception("query option is allow only in streaming!");

        #pragma pack(push, 1)
        struct temperature
        {
            uint8_t is_projector_valid;
            uint8_t is_asic_valid;
            int8_t projector_temperature;
            int8_t asic_temperature;
        };
        #pragma pack(pop)

        auto temperature_data = static_cast<temperature>(_ep.invoke_powered(
            [this](uvc::uvc_device& dev)
            {
                temperature temp{};
                if (!dev.get_xu(ds::depth_xu,
                                ds::DS5_ASIC_AND_PROJECTOR_TEMPERATURES,
                                reinterpret_cast<uint8_t*>(&temp),
                                sizeof(temperature)))
                 {
                        throw invalid_value_exception(to_string() << "get_xu(ctrl=DS5_ASIC_AND_PROJECTOR_TEMPERATURES) failed!" << " Last Error: " << strerror(errno));
                 }

                return temp;
            }));

        int8_t temperature::* feild;
        uint8_t temperature::* is_valid_feild;

        switch (_option)
        {
        case RS2_OPTION_ASIC_TEMPERATURE:
            feild = &temperature::asic_temperature;
            is_valid_feild = &temperature::is_asic_valid;
            break;
        case RS2_OPTION_PROJECTOR_TEMPERATURE:
            feild = &temperature::projector_temperature;
            is_valid_feild = &temperature::is_projector_valid;
            break;
        default:
            throw invalid_value_exception(to_string() << rs2_option_to_string(_option) << " is not temperature option!");
        }

        if (!static_cast<bool>(temperature_data.*is_valid_feild))
            throw invalid_value_exception(to_string() << rs2_option_to_string(_option) << " value is not valid!");

        return temperature_data.*feild;
    }

    option_range asic_and_projector_temperature_options::get_range() const
    {
        return option_range { -40, 125, 0, 0 };
    }

    bool asic_and_projector_temperature_options::is_enabled() const
    {
        return _ep.is_streaming();
    }

    const char* asic_and_projector_temperature_options::get_description() const
    {
        switch (_option)
        {
        case RS2_OPTION_ASIC_TEMPERATURE:
            return "Current Asic Temperature";
        case RS2_OPTION_PROJECTOR_TEMPERATURE:
            return "Current Projector Temperature";
        default:
            throw invalid_value_exception(to_string() << rs2_option_to_string(_option) << " is not temperature option!");
        }
    }

    asic_and_projector_temperature_options::asic_and_projector_temperature_options(uvc_endpoint& ep, rs2_option opt)
        : _option(opt), _ep(ep)
        {}

    float motion_module_temperature_option::query() const
    {
        if (!is_enabled())
            throw wrong_api_call_sequence_exception("query option is allow only in streaming!");

        static const auto report_field = uvc::custom_sensor_report_field::value;
        auto data = _ep.get_custom_report_data(custom_sensor_name, report_name, report_field);
        if (data.empty())
            throw invalid_value_exception("query() motion_module_temperature_option failed! Empty buffer arrived.");

        auto data_str = std::string(reinterpret_cast<char const*>(data.data()));
        return std::stof(data_str);
    }

    option_range motion_module_temperature_option::get_range() const
    {
        if (!is_enabled())
            throw wrong_api_call_sequence_exception("get option range is allow only in streaming!");

        static const auto min_report_field = uvc::custom_sensor_report_field::minimum;
        static const auto max_report_field = uvc::custom_sensor_report_field::maximum;
        auto min_data = _ep.get_custom_report_data(custom_sensor_name, report_name, min_report_field);
        if (min_data.empty())
            throw invalid_value_exception("get_range() motion_module_temperature_option failed! Empty buffer arrived.");

        auto max_data = _ep.get_custom_report_data(custom_sensor_name, report_name, max_report_field);
        if (max_data.empty())
            throw invalid_value_exception("get_range() motion_module_temperature_option failed! Empty buffer arrived.");

        auto min_str = std::string(reinterpret_cast<char const*>(min_data.data()));
        auto max_str = std::string(reinterpret_cast<char const*>(max_data.data()));

        return option_range{std::stof(min_str),
                            std::stof(max_str),
                            0, 0};
    }

    bool motion_module_temperature_option::is_enabled() const
    {
        return _ep.is_streaming();
    }

    const char* motion_module_temperature_option::get_description() const
    {
        return "Current Motion-Module Temperature";
    }

    motion_module_temperature_option::motion_module_temperature_option(hid_endpoint& ep)
        : _ep(ep)
    {}

    void enable_motion_correction::set(float value)
    {
        _is_enabled = value > 0;
    }

    float enable_motion_correction::query() const
    {
        auto is_enabled = _is_enabled.load();
        return is_enabled ? 1.f : 0.f;
    }

    enable_motion_correction::enable_motion_correction(endpoint* mm_ep,
                                                       ds::imu_intrinsics accel,
                                                       ds::imu_intrinsics gyro)
        : _is_enabled(true), _accel(accel), _gyro(gyro)
    {
        mm_ep->register_on_before_frame_callback(
                    [this](rs2_stream stream, rs2_frame& f, callback_invocation_holder callback)
        {
            auto fr = f.get();
            if (_is_enabled.load() && fr->get_format() == RS2_FORMAT_MOTION_XYZ32F)
            {
                auto xyz = (float*)(fr->get_frame_data());

                if (stream == RS2_STREAM_ACCEL)
                {
                    for (int i = 0; i < 3; i++)
                        xyz[i] = xyz[i] * _accel.scale[i] - _accel.bias[i];
                }

                if (stream == RS2_STREAM_GYRO)
                {
                    for (int i = 0; i < 3; i++)
                        xyz[i] = xyz[i] * _gyro.scale[i] - _gyro.bias[i];
                }
            }
        });
    }

    void enable_auto_exposure_option::set(float value)
    {
        if (value <0 ) throw invalid_value_exception("Invalid Auto-Exposure mode request " + std::to_string(value));

        auto auto_exposure_prev_state = _auto_exposure_state->get_enable_auto_exposure();
        _auto_exposure_state->set_enable_auto_exposure(0.f < std::fabs(value));

        if (_auto_exposure_state->get_enable_auto_exposure()) // auto_exposure current value
        {
            if (!auto_exposure_prev_state) // auto_exposure previous value
            {
                _to_add_frames = true; // auto_exposure moved from disable to enable
            }
        }
        else
        {
            if (auto_exposure_prev_state)
            {
                _to_add_frames = false; // auto_exposure moved from enable to disable
            }
        }
    }

    float enable_auto_exposure_option::query() const
    {
        return _auto_exposure_state->get_enable_auto_exposure();
    }

    enable_auto_exposure_option::enable_auto_exposure_option(uvc_endpoint* fisheye_ep,
                                std::shared_ptr<auto_exposure_mechanism> auto_exposure,
                                std::shared_ptr<auto_exposure_state> auto_exposure_state)
        : _auto_exposure_state(auto_exposure_state),
          _to_add_frames((_auto_exposure_state->get_enable_auto_exposure())),
          _auto_exposure(auto_exposure)
    {
        fisheye_ep->register_on_before_frame_callback(
                    [this](rs2_stream stream, rs2_frame& f, callback_invocation_holder callback)
        {
            if (!_to_add_frames || stream != RS2_STREAM_FISHEYE)
                return;

            _auto_exposure->add_frame(f.get()->get_owner()->clone_frame(&f), std::move(callback));
        });
    }

    auto_exposure_mode_option::auto_exposure_mode_option(
                              std::shared_ptr<auto_exposure_mechanism> auto_exposure,
                              std::shared_ptr<auto_exposure_state> auto_exposure_state)
        : _auto_exposure_state(auto_exposure_state),
          _auto_exposure(auto_exposure)
    {}

    void auto_exposure_mode_option::set(float value)
    {
        _auto_exposure_state->set_auto_exposure_mode(static_cast<auto_exposure_modes>((int)value));
        _auto_exposure->update_auto_exposure_state(*_auto_exposure_state);
    }

    float auto_exposure_mode_option::query() const
    {
        return static_cast<float>(_auto_exposure_state->get_auto_exposure_mode());
    }

    const char* auto_exposure_mode_option::get_value_description(float val) const
    {
        switch (static_cast<int>(val))
        {
            case 0:
            {
                return "Static";
            }
            case 1:
            {
                return "Anti-Flicker";
            }
            case 2:
            {
                return "Hybrid";
            }
            default:
                throw invalid_value_exception("value not found");
        }
    }

    auto_exposure_antiflicker_rate_option::auto_exposure_antiflicker_rate_option(
                                          std::shared_ptr<auto_exposure_mechanism> auto_exposure,
                                          std::shared_ptr<auto_exposure_state> auto_exposure_state)
        : _auto_exposure_state(auto_exposure_state),
          _auto_exposure(auto_exposure)
    {}

    void auto_exposure_antiflicker_rate_option::set(float value)
    {
        _auto_exposure_state->set_auto_exposure_antiflicker_rate(static_cast<uint32_t>(value));
        _auto_exposure->update_auto_exposure_state(*_auto_exposure_state);
    }

    float auto_exposure_antiflicker_rate_option::query() const
    {
        return static_cast<float>(_auto_exposure_state->get_auto_exposure_antiflicker_rate());
    }

    const char* auto_exposure_antiflicker_rate_option::get_value_description(float val) const
    {
        switch (static_cast<int>(val))
        {
            case 50:
            {
                return "50Hz";
            }
            case 60:
            {
                return "60Hz";
            }
            default:
                throw invalid_value_exception("antiflicker_rate: get_value_description(...) failed. value not found!");
        }
    }

    ds::depth_table_control depth_scale_option::get_depth_table(ds::advnaced_query_mode mode) const
    {
        command cmd(ds::GET_ADV);
        cmd.param1 = ds::etDepthTableControl;
        cmd.param2 = mode;
        auto res = _hwm.send(cmd);

        if (res.size() < sizeof(ds::depth_table_control))
            throw std::runtime_error("Not enough bytes returned from the firmware!");

        auto table = (const ds::depth_table_control*)res.data();
        return *table;
    }

    depth_scale_option::depth_scale_option(hw_monitor& hwm)
        : _hwm(hwm)
    {
        _range = [this]()
        {
            auto min = get_depth_table(ds::GET_MIN);
            auto max = get_depth_table(ds::GET_MAX);
            return option_range{ (float)(0.000001 * min.depth_units),
                                 (float)(0.000001 * max.depth_units),
                                 0.000001f, 0.001f };
        };
    }

    void depth_scale_option::set(float value)
    {
        command cmd(ds::SET_ADV);
        cmd.param1 = ds::etDepthTableControl;

        auto depth_table = get_depth_table(ds::GET_VAL);
        depth_table.depth_units = 1000000 * value;
        auto ptr = (uint8_t*)(&depth_table);
        cmd.data = std::vector<uint8_t>(ptr, ptr + sizeof(ds::depth_table_control));

        _hwm.send(cmd);
    }

    float depth_scale_option::query() const
    {
        auto table = get_depth_table(ds::GET_VAL);
        return (float)(0.000001 * table.depth_units);
    }

    option_range depth_scale_option::get_range() const
    {
        return *_range;
    }
}
<|endoftext|>


<commit_before>// Creative Commons has made the contents of this file
// available under a CC-GNU-LGPL license:
//
// http://creativecommons.org/licenses/LGPL/2.1/
//
// A copy of the full license can be found as part of this
// distribution in the file COPYING.
//
// You may use the liblicense software in accordance with the
// terms of that license. You agree that you are solely
// responsible for your use of the liblicense software and you
// represent and warrant to Creative Commons that your use
// of the liblicense software will comply with the CC-GNU-LGPL.
//
// Copyright 2007, Creative Commons, www.creativecommons.org.
// Copyright 2007, Jason Kivlighn.

#include <string.h>

#include <liblicense.h>

#include <fileref.h>

#include <mpcfile.h>
#include <vorbisfile.h>
#include <oggflacfile.h>
#include <flacfile.h>

#include <apetag.h>
#include <xiphcomment.h>

using namespace TagLib;

void taglib_init()
{
}

char* readXiphComment( Ogg::XiphComment *tag )
{
	if (tag) {
		const Ogg::FieldListMap fieldListMap =tag->fieldListMap();
		Ogg::FieldListMap::ConstIterator it = fieldListMap.find("LICENSE");
		if (it != fieldListMap.end()) {
			return strdup(it->second.front().toCString());
		}
	}

	return NULL;
}

char* taglib_read( const char* filename , const char * predicate)
{
	FileRef fileref(filename, false);

	File *file = fileref.file();
	if (file) {
		if (dynamic_cast<MPC::File*>(file)) {
			APE::Tag *tag = ((MPC::File*)(file))->APETag();
			if (tag) {
				const APE::ItemListMap itemListMap = tag->itemListMap();
				APE::ItemListMap::ConstIterator it = itemListMap.find("LICENSE");
				if (it != itemListMap.end()) {
					return strdup(it->second.value().data());
				}
			}
		} else if (dynamic_cast<Ogg::Vorbis::File*>(file)) {
			Ogg::XiphComment *tag = ((Ogg::Vorbis::File*)(file))->tag();
			return readXiphComment(tag);
		} else if (dynamic_cast<FLAC::File*>(file)) {
			Ogg::XiphComment *tag = ((FLAC::File*)(file))->xiphComment();
			return readXiphComment(tag);
		} else if (dynamic_cast<Ogg::FLAC::File*>(file)) {
			Ogg::XiphComment *tag = ((Ogg::FLAC::File*)(file))->tag();
			return readXiphComment(tag);
		}
	}

	return NULL;
}

int taglib_write( const char* filename, const char * predicate, const char* uri )
{
	FileRef fileref(filename, false);
	File *file = fileref.file();
	if (file) {
		if (dynamic_cast<MPC::File*>(file)) {
			APE::Tag *tag = ((MPC::File*)(file))->APETag(uri!=NULL);
			if (uri) {
				tag->addValue("LICENSE",uri);
			} else if (tag) {
				tag->removeItem("LICENSE");
			}
			return fileref.save();
		} else if (dynamic_cast<Ogg::Vorbis::File*>(file)) {
			Ogg::XiphComment *tag = ((Ogg::Vorbis::File*)(file))->tag();
			if (uri) {
				tag->addField("LICENSE",uri,true);
			} else if (tag) {
				tag->removeField("LICENSE");
			}
			return fileref.save();
		} else if (dynamic_cast<FLAC::File*>(file)) {
			Ogg::XiphComment *tag = ((FLAC::File*)(file))->xiphComment(uri!=NULL);
			if (uri) {
				tag->addField("LICENSE",uri,true);
			} else if (tag) {
				tag->removeField("LICENSE");
			}
			return fileref.save();
		} else if (dynamic_cast<Ogg::FLAC::File*>(file)) {
			Ogg::XiphComment *tag = ((Ogg::FLAC::File*)(file))->tag();
			if (uri) {
				tag->addField("LICENSE",uri,true);
			} else if (tag) {
				tag->removeField("LICENSE");
			}
			return fileref.save();
		}
	}

	return 0;
}

const char * taglib_supported_predicates[] = {LL_LICENSE,
};
const char * taglib_mime_types[] = {"audio/x-musepack",
				    "audio/x-vorbis+ogg",
				    "application/ogg",
				    "audio/x-flac"};

void taglib_shutdown()
{
  // Do nothing!
}

LL_MODULE_DEFINE("taglib.so", // name
		 "Embeds licenses in tags of formats supported by TagLib.", // description
		 "0.1", // version
		 LL_FEATURES_EMBED, // features
		 taglib_supported_predicates, // supported predicates
		 taglib_mime_types, // supported MIME types
		 taglib_init,
		 taglib_read,
		 taglib_write,
		 taglib_shutdown);
<commit_msg>Put a NULL at the end of the lists of TagLib-compatible MIME types<commit_after>// Creative Commons has made the contents of this file
// available under a CC-GNU-LGPL license:
//
// http://creativecommons.org/licenses/LGPL/2.1/
//
// A copy of the full license can be found as part of this
// distribution in the file COPYING.
//
// You may use the liblicense software in accordance with the
// terms of that license. You agree that you are solely
// responsible for your use of the liblicense software and you
// represent and warrant to Creative Commons that your use
// of the liblicense software will comply with the CC-GNU-LGPL.
//
// Copyright 2007, Creative Commons, www.creativecommons.org.
// Copyright 2007, Jason Kivlighn.

#include <string.h>

#include <liblicense.h>

#include <fileref.h>

#include <mpcfile.h>
#include <vorbisfile.h>
#include <oggflacfile.h>
#include <flacfile.h>

#include <apetag.h>
#include <xiphcomment.h>

using namespace TagLib;

void taglib_init()
{
}

char* readXiphComment( Ogg::XiphComment *tag )
{
	if (tag) {
		const Ogg::FieldListMap fieldListMap =tag->fieldListMap();
		Ogg::FieldListMap::ConstIterator it = fieldListMap.find("LICENSE");
		if (it != fieldListMap.end()) {
			return strdup(it->second.front().toCString());
		}
	}

	return NULL;
}

char* taglib_read( const char* filename , const char * predicate)
{
	FileRef fileref(filename, false);

	File *file = fileref.file();
	if (file) {
		if (dynamic_cast<MPC::File*>(file)) {
			APE::Tag *tag = ((MPC::File*)(file))->APETag();
			if (tag) {
				const APE::ItemListMap itemListMap = tag->itemListMap();
				APE::ItemListMap::ConstIterator it = itemListMap.find("LICENSE");
				if (it != itemListMap.end()) {
					return strdup(it->second.value().data());
				}
			}
		} else if (dynamic_cast<Ogg::Vorbis::File*>(file)) {
			Ogg::XiphComment *tag = ((Ogg::Vorbis::File*)(file))->tag();
			return readXiphComment(tag);
		} else if (dynamic_cast<FLAC::File*>(file)) {
			Ogg::XiphComment *tag = ((FLAC::File*)(file))->xiphComment();
			return readXiphComment(tag);
		} else if (dynamic_cast<Ogg::FLAC::File*>(file)) {
			Ogg::XiphComment *tag = ((Ogg::FLAC::File*)(file))->tag();
			return readXiphComment(tag);
		}
	}

	return NULL;
}

int taglib_write( const char* filename, const char * predicate, const char* uri )
{
	FileRef fileref(filename, false);
	File *file = fileref.file();
	if (file) {
		if (dynamic_cast<MPC::File*>(file)) {
			APE::Tag *tag = ((MPC::File*)(file))->APETag(uri!=NULL);
			if (uri) {
				tag->addValue("LICENSE",uri);
			} else if (tag) {
				tag->removeItem("LICENSE");
			}
			return fileref.save();
		} else if (dynamic_cast<Ogg::Vorbis::File*>(file)) {
			Ogg::XiphComment *tag = ((Ogg::Vorbis::File*)(file))->tag();
			if (uri) {
				tag->addField("LICENSE",uri,true);
			} else if (tag) {
				tag->removeField("LICENSE");
			}
			return fileref.save();
		} else if (dynamic_cast<FLAC::File*>(file)) {
			Ogg::XiphComment *tag = ((FLAC::File*)(file))->xiphComment(uri!=NULL);
			if (uri) {
				tag->addField("LICENSE",uri,true);
			} else if (tag) {
				tag->removeField("LICENSE");
			}
			return fileref.save();
		} else if (dynamic_cast<Ogg::FLAC::File*>(file)) {
			Ogg::XiphComment *tag = ((Ogg::FLAC::File*)(file))->tag();
			if (uri) {
				tag->addField("LICENSE",uri,true);
			} else if (tag) {
				tag->removeField("LICENSE");
			}
			return fileref.save();
		}
	}

	return 0;
}

const char * taglib_supported_predicates[] = {LL_LICENSE,
};
const char * taglib_mime_types[] = {"audio/x-musepack",
				    "audio/x-vorbis+ogg",
				    "application/ogg",
				    "audio/x-flac", NULL};

void taglib_shutdown()
{
  // Do nothing!
}

LL_MODULE_DEFINE("taglib.so", // name
		 "Embeds licenses in tags of formats supported by TagLib.", // description
		 "0.1", // version
		 LL_FEATURES_EMBED, // features
		 taglib_supported_predicates, // supported predicates
		 taglib_mime_types, // supported MIME types
		 taglib_init,
		 taglib_read,
		 taglib_write,
		 taglib_shutdown);
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: lcolitem.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 14:28:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SVX_LCOLITEM_HXX
#define _SVX_LCOLITEM_HXX

// include ---------------------------------------------------------------

#ifndef _SVX_COLRITEM_HXX
#include <svx/colritem.hxx>
#endif
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif

/*
 * dummy-Item fuer ToolBox-Controller:
 *
 */

class SvxLineColorItem : public SvxColorItem
{
public:
    TYPEINFO();

    SvxLineColorItem( const USHORT nId  );
    SvxLineColorItem( const Color& aColor, const USHORT nId  );
    SvxLineColorItem( SvStream& rStrm, const USHORT nId  );
    SvxLineColorItem( const SvxLineColorItem& rCopy );
    ~SvxLineColorItem();

    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
                                    SfxMapUnit eCoreMetric,
                                    SfxMapUnit ePresMetric,
                                    String &rText,
                                    const IntlWrapper * pIntlWrapper = 0 )
        const;

    inline SvxLineColorItem& operator=(const SvxLineColorItem& rColor)
        { return (SvxLineColorItem&)SvxColorItem::
            operator=((const SvxColorItem&)rColor); }

};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.3.446); FILE MERGED 2008/04/01 12:46:43 thb 1.3.446.2: #i85898# Stripping all external header guards 2008/03/31 14:18:13 rt 1.3.446.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: lcolitem.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SVX_LCOLITEM_HXX
#define _SVX_LCOLITEM_HXX

// include ---------------------------------------------------------------

#include <svx/colritem.hxx>
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif

/*
 * dummy-Item fuer ToolBox-Controller:
 *
 */

class SvxLineColorItem : public SvxColorItem
{
public:
    TYPEINFO();

    SvxLineColorItem( const USHORT nId  );
    SvxLineColorItem( const Color& aColor, const USHORT nId  );
    SvxLineColorItem( SvStream& rStrm, const USHORT nId  );
    SvxLineColorItem( const SvxLineColorItem& rCopy );
    ~SvxLineColorItem();

    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
                                    SfxMapUnit eCoreMetric,
                                    SfxMapUnit ePresMetric,
                                    String &rText,
                                    const IntlWrapper * pIntlWrapper = 0 )
        const;

    inline SvxLineColorItem& operator=(const SvxLineColorItem& rColor)
        { return (SvxLineColorItem&)SvxColorItem::
            operator=((const SvxColorItem&)rColor); }

};

#endif

<|endoftext|>


<commit_before><commit_msg>sw: stop using comphelper/implbase_var.hxx<commit_after><|endoftext|>


<commit_before>struct pmc_count {

  static void config(u64 sel) {
    perf_start(sel, 0);
  }

  static pmc_count read(unsigned int ctr) {
    pmc_count n;

    // XXX(sbw) we loose our original affinity
    for (int i = 0; i < NCPU; i++) {
      setaffinity(i);
      n.count_[i] = rdpmc(ctr);
    }
    setaffinity(-1);
    return n;
  }

  pmc_count delta(const pmc_count& o) {
    pmc_count n;

    for (int i = 0; i < NCPU; i++)
      n.count_[i] = count_[i] - o.count_[i];
    return n;
  }

  u64 sum() const {
    u64 tot = 0;

    for (int i = 0; i < NCPU; i++)
      tot += count_[i];
    return tot;
  }

  u64 count_[NCPU];
};
<commit_msg>qemu workaround<commit_after>struct pmc_count {

  static void config(u64 sel) {
    perf_start(sel, 0);
  }

  static pmc_count read(unsigned int ctr) {
    pmc_count n;

    // XXX(sbw) we loose our original affinity
    for (int i = 0; i < NCPU; i++) {
      setaffinity(i);
      // XXX(sbw) qemu doesn't seem to support CR4_PCE
#if defined(HW_qemu)
      n.count_[i] = 0;
#else
      n.count_[i] = rdpmc(ctr);
#endif
    }
    setaffinity(-1);
    return n;
  }

  pmc_count delta(const pmc_count& o) {
    pmc_count n;

    for (int i = 0; i < NCPU; i++)
      n.count_[i] = count_[i] - o.count_[i];
    return n;
  }

  u64 sum() const {
    u64 tot = 0;

    for (int i = 0; i < NCPU; i++)
      tot += count_[i];
    return tot;
  }

  u64 count_[NCPU];
};
<|endoftext|>


<commit_before>#include <algorithm>
#include <vector>
#include <string>
#include <memory>
#include <map>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>

#include "producer.h"

bool is_worker = false;
std::string queue_path;
std::map<std::string, std::unique_ptr<Producer> > producers;

extern "C" {
	#include <ngx_config.h>
	#include <ngx_core.h>
	#include <ngx_http.h>

	static void *ngx_http_lmdb_queue_create_loc_conf(ngx_conf_t *cf);
	static ngx_int_t lmdb_queue_on_init_process(ngx_cycle_t*);
	static void lmdb_queue_on_exit_process(ngx_cycle_t *cycle);

	/* Directive handlers */
	static char *ngx_http_lmdb_queue(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue
	static char *ngx_http_lmdb_queue_topic(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue topic
	static char *ngx_http_lmdb_queue_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue topic

	/* Filter */
	ngx_http_output_body_filter_pt ngx_http_next_body_filter;
	static ngx_int_t ngx_http_lmdb_queue_handler_init(ngx_conf_t *cf);
	static ngx_int_t ngx_http_lmdb_queue_handler(ngx_http_request_t *r);

	/* Directives */
	static ngx_command_t ngx_http_lmdb_queue_commands[] = {
		{ ngx_string("lmdb_queue"),
		  NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1,
		  ngx_http_lmdb_queue,
		  NGX_HTTP_MAIN_CONF_OFFSET,
		  0,
		  NULL },
		{ ngx_string("lmdb_queue_topic"),
		  NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE3,
		  ngx_http_lmdb_queue_topic,
		  NGX_HTTP_MAIN_CONF_OFFSET,
		  0,
		  NULL },
		{ ngx_string("lmdb_queue_push"),
		  NGX_HTTP_SRV_CONF | NGX_HTTP_LOC_CONF | NGX_CONF_TAKE2,
		  ngx_http_lmdb_queue_push,
		  NGX_HTTP_LOC_CONF_OFFSET,
		  0,
		  NULL },
		ngx_null_command
	};

	static ngx_http_module_t ngx_http_lmdb_queue_module_ctx = {
		NULL, /* preconfiguration */
		ngx_http_lmdb_queue_handler_init, /* postconfiguration */

		NULL, /* create main configuration */
		NULL, /* init main configuration */

		NULL, /* create server configuration */
		NULL, /* merge server configuration */

		ngx_http_lmdb_queue_create_loc_conf, /* create location configuration */
		NULL  /* merge location configuration */
	};

	ngx_module_t ngx_http_lmdb_queue_module = {
		NGX_MODULE_V1,
		&ngx_http_lmdb_queue_module_ctx,       /* module context */
		ngx_http_lmdb_queue_commands,          /* module directives */
		NGX_HTTP_MODULE,                       /* module type */
		NULL,                                  /* init master */
		NULL,                                  /* init module */
		lmdb_queue_on_init_process,            /* init process */
		NULL,                                  /* init thread */
		NULL,                                  /* exit thread */
		lmdb_queue_on_exit_process,            /* exit process */
		NULL,                                  /* exit master */
		NGX_MODULE_V1_PADDING
	};

	struct ngx_http_lmdb_queue_loc_conf {
		Producer* producer;

		size_t data_format_len;
		u_char data_format[1024 * 8];

		size_t vars_count;
		ngx_int_t* vars;
	};

	static void *ngx_http_lmdb_queue_create_loc_conf(ngx_conf_t *cf) {
		ngx_http_lmdb_queue_loc_conf *conf = (ngx_http_lmdb_queue_loc_conf*)ngx_pcalloc(cf->pool, sizeof(ngx_http_lmdb_queue_loc_conf));
		if (conf == NULL) {
			return NGX_CONF_ERROR;
		}

		ngx_memzero(conf, sizeof(ngx_http_lmdb_queue_loc_conf));
		return conf;
	}

	static char *ngx_http_lmdb_queue(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
		ngx_str_t *args = (ngx_str_t*)cf->args->elts;
		const char *path = (const char*)args[1].data;
		int res = mkdir(path, 0766);
		if (res == 0 || errno == EEXIST) {
			queue_path = path;
			return NGX_CONF_OK;
		} else {
			ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V %s", &args[1], strerror(errno));
			return (char*)NGX_CONF_ERROR;
		}
	}

	static char *ngx_http_lmdb_queue_topic(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
		ngx_str_t *args = (ngx_str_t*)cf->args->elts;
		const char *name = (const char*)args[1].data;

		const char *chunkSizeStr = (const char*)args[2].data;
		size_t chunkSize = strtoull(chunkSizeStr, NULL, 10);
		if (chunkSize == ULLONG_MAX) {
			ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V %s", &args[2], strerror(errno));
			return (char*)NGX_CONF_ERROR;
		}

		char unit = chunkSizeStr[args[2].len - 1];
		switch (unit) {
			case 'm':
			case 'M':
				chunkSize *= 1024 * 1024;
				break;
			case 'g':
			case 'G':
				chunkSize *= 1024 * 1024 * 1024;
				break;
			default:
				ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: Invalid topic chunk size unit(should be m|g).", &args[2]);
				return (char*)NGX_CONF_ERROR;
		}

		if (chunkSize < 64 * 1024 * 1024 || chunkSize > size_t(64) * 1024 * 1024 * 1024) {
			ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: Invalid topic chunk size unit(should between 64MB and 64GB).", &args[2]);
			return (char*)NGX_CONF_ERROR;
		}

		size_t chunksToKeep = strtoull((const char*)args[3].data, NULL, 10);
		if (chunksToKeep == ULLONG_MAX) {
			ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: %s", &args[2], strerror(errno));
			return (char*)NGX_CONF_ERROR;
		}
		if (chunksToKeep < 4) {
			ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: You should keep at least 4 chunks.", &args[3]);
			return (char*)NGX_CONF_ERROR;
		}

		//printf("Args: %s %zu %zu", name, chunkSize, chunksToKeep);
		auto &ptr = producers[name];
		if (ptr.get() == NULL) {
			TopicOpt qopt = { chunkSize, chunksToKeep };
			ptr.reset(new Producer(queue_path, name, &qopt));
			if (is_worker) {
				ptr->enableBackgroundFlush();
			} else {
				ptr.reset(nullptr);
			}
		}

		return NGX_CONF_OK;
	}

	static char *ngx_http_lmdb_queue_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
		ngx_str_t *args = (ngx_str_t*)cf->args->elts;

		const char *topic = (const char*)args[1].data;
		auto producerIter = producers.find(topic);

		if (producerIter == producers.end()) {
			ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "Topic '%V' not exists.", &args[1]);
			return (char*)NGX_CONF_ERROR;
		}

		ngx_http_lmdb_queue_loc_conf *locconf = (ngx_http_lmdb_queue_loc_conf*)conf;

		std::vector<ngx_int_t> varIndexes;
		u_char *end = args[2].data + args[2].len, *varCur = NULL, *outCur = locconf->data_format;
		for (u_char *s = args[2].data; s < end;) {
			if (*s == '$') {
				varCur = ++s;
				*outCur++ = '\1';
				while (s < end && ((*s >= '0' && *s <= '9') || (*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || *s == '_')) {
					++s;
				}

				ngx_str_t varName { size_t(s - varCur), varCur };
				ngx_int_t idx = ngx_http_get_variable_index(cf, &varName);
				if (idx == NGX_ERROR) {
					return (char*)NGX_CONF_ERROR;
				}

				varIndexes.push_back(idx);
				continue;
			}

			if (*s == '\\' && s + 1 < end) {
				if (*(s + 1) == '0') {
					*outCur++ = 0;
					s += 2;
					continue;
				}

				if (*(s + 1) == '$' || *(s + 1) == '\\') {
					*outCur++ = *(s + 1);
					s += 2;
					continue;
				}
			}

			*outCur++ = *s++;
		}

		locconf->data_format_len = size_t(outCur - locconf->data_format);
		locconf->producer = producerIter->second.get();
		locconf->vars_count = varIndexes.size();
		locconf->vars = (ngx_int_t*)ngx_pcalloc(cf->pool, varIndexes.size() * sizeof(ngx_int_t));
		std::copy(varIndexes.begin(), varIndexes.end(), locconf->vars);

		return NGX_CONF_OK;
	}

	static ngx_int_t ngx_http_lmdb_queue_handler_init(ngx_conf_t *cf) {
		ngx_http_core_main_conf_t *cmcf = (ngx_http_core_main_conf_t*)ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);
		ngx_http_handler_pt *h = (ngx_http_handler_pt*)ngx_array_push(&cmcf->phases[NGX_HTTP_LOG_PHASE].handlers);
		if (h == NULL) {
			return NGX_ERROR;
		}

		*h = ngx_http_lmdb_queue_handler;
		return NGX_OK;
	}

	static ngx_int_t ngx_http_lmdb_queue_handler(ngx_http_request_t *r) {
		ngx_http_lmdb_queue_loc_conf *lcf = (ngx_http_lmdb_queue_loc_conf*)ngx_http_get_module_loc_conf(r, ngx_http_lmdb_queue_module);
		if (lcf->producer == NULL) {
			return NGX_OK;
		}

		std::vector<ngx_http_variable_value_t*> vals;
		size_t resLen = lcf->data_format_len;
		for (size_t i = 0; i < lcf->vars_count; ++i) {
			ngx_http_variable_value_t *v = ngx_http_get_indexed_variable(r, lcf->vars[i]);
			vals.push_back(v);

			if (v && !v->not_found) {
				resLen += (v->len - 1);
			} else {
				--resLen;
			}
		}

		Producer::ItemType item = Producer::ItemType::create(resLen);
		u_char *formatCur = lcf->data_format, *formatEnd = lcf->data_format + lcf->data_format_len;
		u_char *cur = (u_char*)item.data();
		auto valIter = vals.begin();
		while (formatCur < formatEnd) {
			if (*formatCur != '\1') {
				*cur++ = *formatCur++;
			} else {
				++formatCur;
				ngx_http_variable_value_t *v = *valIter++;
				if (v && !v->not_found) {
					for (u_char *src = v->data; src < v->data + v->len;) {
						*cur++ = *src++;
					}
				}
			}
		}

		lcf->producer->push2Cache(std::move(item));
		return NGX_OK;
	}

	ngx_int_t lmdb_queue_on_init_process(ngx_cycle_t*) {
		is_worker = true;
		return NGX_OK;
	}

	void lmdb_queue_on_exit_process(ngx_cycle_t*) {
		producers.clear();
	}
}<commit_msg>rollback<commit_after>#include <algorithm>
#include <vector>
#include <string>
#include <memory>
#include <map>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>

#include "producer.h"

std::string queue_path;
std::map<std::string, std::unique_ptr<Producer> > producers;

extern "C" {
	#include <ngx_config.h>
	#include <ngx_core.h>
	#include <ngx_http.h>

	static void *ngx_http_lmdb_queue_create_loc_conf(ngx_conf_t *cf);
	static ngx_int_t lmdb_queue_on_init_process(ngx_cycle_t*);
	static void lmdb_queue_on_exit_process(ngx_cycle_t *cycle);

	/* Directive handlers */
	static char *ngx_http_lmdb_queue(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue
	static char *ngx_http_lmdb_queue_topic(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue topic
	static char *ngx_http_lmdb_queue_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue topic

	/* Filter */
	ngx_http_output_body_filter_pt ngx_http_next_body_filter;
	static ngx_int_t ngx_http_lmdb_queue_handler_init(ngx_conf_t *cf);
	static ngx_int_t ngx_http_lmdb_queue_handler(ngx_http_request_t *r);

	/* Directives */
	static ngx_command_t ngx_http_lmdb_queue_commands[] = {
		{ ngx_string("lmdb_queue"),
		  NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1,
		  ngx_http_lmdb_queue,
		  NGX_HTTP_MAIN_CONF_OFFSET,
		  0,
		  NULL },
		{ ngx_string("lmdb_queue_topic"),
		  NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE3,
		  ngx_http_lmdb_queue_topic,
		  NGX_HTTP_MAIN_CONF_OFFSET,
		  0,
		  NULL },
		{ ngx_string("lmdb_queue_push"),
		  NGX_HTTP_SRV_CONF | NGX_HTTP_LOC_CONF | NGX_CONF_TAKE2,
		  ngx_http_lmdb_queue_push,
		  NGX_HTTP_LOC_CONF_OFFSET,
		  0,
		  NULL },
		ngx_null_command
	};

	static ngx_http_module_t ngx_http_lmdb_queue_module_ctx = {
		NULL, /* preconfiguration */
		ngx_http_lmdb_queue_handler_init, /* postconfiguration */

		NULL, /* create main configuration */
		NULL, /* init main configuration */

		NULL, /* create server configuration */
		NULL, /* merge server configuration */

		ngx_http_lmdb_queue_create_loc_conf, /* create location configuration */
		NULL  /* merge location configuration */
	};

	ngx_module_t ngx_http_lmdb_queue_module = {
		NGX_MODULE_V1,
		&ngx_http_lmdb_queue_module_ctx,       /* module context */
		ngx_http_lmdb_queue_commands,          /* module directives */
		NGX_HTTP_MODULE,                       /* module type */
		NULL,                                  /* init master */
		NULL,                                  /* init module */
		lmdb_queue_on_init_process,            /* init process */
		NULL,                                  /* init thread */
		NULL,                                  /* exit thread */
		lmdb_queue_on_exit_process,            /* exit process */
		NULL,                                  /* exit master */
		NGX_MODULE_V1_PADDING
	};

	struct ngx_http_lmdb_queue_loc_conf {
		Producer* producer;

		size_t data_format_len;
		u_char data_format[1024 * 8];

		size_t vars_count;
		ngx_int_t* vars;
	};

	static void *ngx_http_lmdb_queue_create_loc_conf(ngx_conf_t *cf) {
		ngx_http_lmdb_queue_loc_conf *conf = (ngx_http_lmdb_queue_loc_conf*)ngx_pcalloc(cf->pool, sizeof(ngx_http_lmdb_queue_loc_conf));
		if (conf == NULL) {
			return NGX_CONF_ERROR;
		}

		ngx_memzero(conf, sizeof(ngx_http_lmdb_queue_loc_conf));
		return conf;
	}

	static char *ngx_http_lmdb_queue(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
		ngx_str_t *args = (ngx_str_t*)cf->args->elts;
		const char *path = (const char*)args[1].data;
		int res = mkdir(path, 0766);
		if (res == 0 || errno == EEXIST) {
			queue_path = path;
			return NGX_CONF_OK;
		} else {
			ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V %s", &args[1], strerror(errno));
			return (char*)NGX_CONF_ERROR;
		}
	}

	static char *ngx_http_lmdb_queue_topic(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
		ngx_str_t *args = (ngx_str_t*)cf->args->elts;
		const char *name = (const char*)args[1].data;

		const char *chunkSizeStr = (const char*)args[2].data;
		size_t chunkSize = strtoull(chunkSizeStr, NULL, 10);
		if (chunkSize == ULLONG_MAX) {
			ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V %s", &args[2], strerror(errno));
			return (char*)NGX_CONF_ERROR;
		}

		char unit = chunkSizeStr[args[2].len - 1];
		switch (unit) {
			case 'm':
			case 'M':
				chunkSize *= 1024 * 1024;
				break;
			case 'g':
			case 'G':
				chunkSize *= 1024 * 1024 * 1024;
				break;
			default:
				ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: Invalid topic chunk size unit(should be m|g).", &args[2]);
				return (char*)NGX_CONF_ERROR;
		}

		if (chunkSize < 64 * 1024 * 1024 || chunkSize > size_t(64) * 1024 * 1024 * 1024) {
			ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: Invalid topic chunk size unit(should between 64MB and 64GB).", &args[2]);
			return (char*)NGX_CONF_ERROR;
		}

		size_t chunksToKeep = strtoull((const char*)args[3].data, NULL, 10);
		if (chunksToKeep == ULLONG_MAX) {
			ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: %s", &args[2], strerror(errno));
			return (char*)NGX_CONF_ERROR;
		}
		if (chunksToKeep < 4) {
			ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V: You should keep at least 4 chunks.", &args[3]);
			return (char*)NGX_CONF_ERROR;
		}

		//printf("Args: %s %zu %zu", name, chunkSize, chunksToKeep);
		auto &ptr = producers[name];
		if (ptr.get() == NULL) {
			TopicOpt qopt = { chunkSize, chunksToKeep };
			ptr.reset(new Producer(queue_path, name, &qopt));
		}

		return NGX_CONF_OK;
	}

	static char *ngx_http_lmdb_queue_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
		ngx_str_t *args = (ngx_str_t*)cf->args->elts;

		const char *topic = (const char*)args[1].data;
		auto producerIter = producers.find(topic);

		if (producerIter == producers.end()) {
			ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "Topic '%V' not exists.", &args[1]);
			return (char*)NGX_CONF_ERROR;
		}

		ngx_http_lmdb_queue_loc_conf *locconf = (ngx_http_lmdb_queue_loc_conf*)conf;

		std::vector<ngx_int_t> varIndexes;
		u_char *end = args[2].data + args[2].len, *varCur = NULL, *outCur = locconf->data_format;
		for (u_char *s = args[2].data; s < end;) {
			if (*s == '$') {
				varCur = ++s;
				*outCur++ = '\1';
				while (s < end && ((*s >= '0' && *s <= '9') || (*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || *s == '_')) {
					++s;
				}

				ngx_str_t varName { size_t(s - varCur), varCur };
				ngx_int_t idx = ngx_http_get_variable_index(cf, &varName);
				if (idx == NGX_ERROR) {
					return (char*)NGX_CONF_ERROR;
				}

				varIndexes.push_back(idx);
				continue;
			}

			if (*s == '\\' && s + 1 < end) {
				if (*(s + 1) == '0') {
					*outCur++ = 0;
					s += 2;
					continue;
				}

				if (*(s + 1) == '$' || *(s + 1) == '\\') {
					*outCur++ = *(s + 1);
					s += 2;
					continue;
				}
			}

			*outCur++ = *s++;
		}

		locconf->data_format_len = size_t(outCur - locconf->data_format);
		locconf->producer = producerIter->second.get();
		locconf->vars_count = varIndexes.size();
		locconf->vars = (ngx_int_t*)ngx_pcalloc(cf->pool, varIndexes.size() * sizeof(ngx_int_t));
		std::copy(varIndexes.begin(), varIndexes.end(), locconf->vars);

		return NGX_CONF_OK;
	}

	static ngx_int_t ngx_http_lmdb_queue_handler_init(ngx_conf_t *cf) {
		ngx_http_core_main_conf_t *cmcf = (ngx_http_core_main_conf_t*)ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);
		ngx_http_handler_pt *h = (ngx_http_handler_pt*)ngx_array_push(&cmcf->phases[NGX_HTTP_LOG_PHASE].handlers);
		if (h == NULL) {
			return NGX_ERROR;
		}

		*h = ngx_http_lmdb_queue_handler;
		return NGX_OK;
	}

	static ngx_int_t ngx_http_lmdb_queue_handler(ngx_http_request_t *r) {
		ngx_http_lmdb_queue_loc_conf *lcf = (ngx_http_lmdb_queue_loc_conf*)ngx_http_get_module_loc_conf(r, ngx_http_lmdb_queue_module);
		if (lcf->producer == NULL) {
			return NGX_OK;
		}

		std::vector<ngx_http_variable_value_t*> vals;
		size_t resLen = lcf->data_format_len;
		for (size_t i = 0; i < lcf->vars_count; ++i) {
			ngx_http_variable_value_t *v = ngx_http_get_indexed_variable(r, lcf->vars[i]);
			vals.push_back(v);

			if (v && !v->not_found) {
				resLen += (v->len - 1);
			} else {
				--resLen;
			}
		}

		Producer::ItemType item = Producer::ItemType::create(resLen);
		u_char *formatCur = lcf->data_format, *formatEnd = lcf->data_format + lcf->data_format_len;
		u_char *cur = (u_char*)item.data();
		auto valIter = vals.begin();
		while (formatCur < formatEnd) {
			if (*formatCur != '\1') {
				*cur++ = *formatCur++;
			} else {
				++formatCur;
				ngx_http_variable_value_t *v = *valIter++;
				if (v && !v->not_found) {
					for (u_char *src = v->data; src < v->data + v->len;) {
						*cur++ = *src++;
					}
				}
			}
		}

		lcf->producer->push2Cache(std::move(item));
		return NGX_OK;
	}

	ngx_int_t lmdb_queue_on_init_process(ngx_cycle_t*) {
		for (auto &producer : producers) {
			producer.second->enableBackgroundFlush();
		}

		return NGX_OK;
	}

	void lmdb_queue_on_exit_process(ngx_cycle_t*) {
		producers.clear();
	}
}<|endoftext|>


<commit_before>#include "gtest/gtest.h"
#include "c7a/data/data_manager.hpp"

using namespace c7a::data;

TEST(DataManager, GetLocalBlockReturnsEmptyIteratorIfNotFound) {
    DataManager manager;
    auto it = manager.getLocalBlocks<int>(0);
    ASSERT_FALSE(it.has_next());
}
<commit_msg>update DataManager Tests<commit_after>#include "gtest/gtest.h"
#include "c7a/data/data_manager.hpp"

using namespace c7a::data;

TEST(DataManager, GetLocalBlock_FailsIfNotFound) {
    DataManager manager;
    ASSERT_ANY_THROW(manager.getLocalBlocks<int>(0));
}

TEST(DataManager, GetLocalEmitter_FailsIfNotFound) {
    DataManager manager;
    ASSERT_ANY_THROW(manager.getLocalEmitter<int>(0));
}
<|endoftext|>