<commit_before>#if ! defined (__CINT__) || defined (__MAKECINT__)
#include "TTree.h"
#include "AliLog.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "PWG1/TRD/macros/AliTRDperformanceTrain.h"
#include "PWG1/TRD/AliTRDv0Monitor.h"
#endif

#include "PWG1/TRD/macros/helper.C"
void AddTRDv0Monitor(AliAnalysisManager *mgr, Char_t *trd, AliAnalysisDataContainer **ci/*, AliAnalysisDataContainer **co*/)
{
  Int_t map = ParseOptions(trd);
  if(!TSTBIT(map, kV0Monitor)) return;
  printf("AddTRDv0Monitor <- [0]=\"%s\" [1]=\"%s\" [2]=\"%s\"\n", ci[0]->GetName(), ci[1]->GetName(), ci[2]->GetName());

  AliTRDv0Monitor *v0Mon = new AliTRDv0Monitor((char*()"TRDv0Monitor"));
  mgr->AddTask(v0Mon);
  v0Mon->SetDebugLevel(0);
  //AliLog::SetClassDebugLevel("AliTRDpidRefMaker", 3);
  v0Mon->SetMCdata(mgr->GetMCtruthEventHandler());
  v0Mon->SetFriends(kTRUE);
  //v0Mon->SetSource(AliTRDpidRefMaker::kV0,AliTRDpidRefMaker::kRec);
  mgr->ConnectInput( v0Mon, 0, mgr->GetCommonInputContainer());
  mgr->ConnectInput( v0Mon, 1, ci[0]);
  mgr->ConnectInput( v0Mon, 2, ci[1]);
  mgr->ConnectInput( v0Mon, 3, ci[2]);

  mgr->ConnectOutput(v0Mon, 1, mgr->CreateContainer(v0Mon->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TRD_Performance",mgr->GetCommonFileName())));
  //mgr->ConnectOutput(v0Mon, 2, mgr->CreateContainer(v0Mon->GetName(), TTree::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TRD.CalibPIDrefMaker", mgr->GetCommonFileName())));
}

<commit_msg>fix cast statement<commit_after>#if ! defined (__CINT__) || defined (__MAKECINT__)
#include "TTree.h"
#include "AliLog.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "PWG1/TRD/macros/AliTRDperformanceTrain.h"
#include "PWG1/TRD/AliTRDv0Monitor.h"
#endif

#include "PWG1/TRD/macros/helper.C"
void AddTRDv0Monitor(AliAnalysisManager *mgr, Char_t *trd, AliAnalysisDataContainer **ci/*, AliAnalysisDataContainer **co*/)
{
  Int_t map = ParseOptions(trd);
  if(!TSTBIT(map, kV0Monitor)) return;
  printf("AddTRDv0Monitor <- [0]=\"%s\" [1]=\"%s\" [2]=\"%s\"\n", ci[0]->GetName(), ci[1]->GetName(), ci[2]->GetName());

  AliTRDv0Monitor *v0Mon(NULL);;
  mgr->AddTask(v0Mon = new AliTRDv0Monitor((char*)"TRDv0Monitor"));
  v0Mon->SetDebugLevel(0);
  //AliLog::SetClassDebugLevel("AliTRDpidRefMaker", 3);
  v0Mon->SetMCdata(mgr->GetMCtruthEventHandler());
  v0Mon->SetFriends(kTRUE);
  //v0Mon->SetSource(AliTRDpidRefMaker::kV0,AliTRDpidRefMaker::kRec);
  mgr->ConnectInput( v0Mon, 0, mgr->GetCommonInputContainer());
  mgr->ConnectInput( v0Mon, 1, ci[0]);
  mgr->ConnectInput( v0Mon, 2, ci[1]);
  mgr->ConnectInput( v0Mon, 3, ci[2]);

  mgr->ConnectOutput(v0Mon, 1, mgr->CreateContainer(v0Mon->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TRD_Performance",mgr->GetCommonFileName())));
  //mgr->ConnectOutput(v0Mon, 2, mgr->CreateContainer(v0Mon->GetName(), TTree::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TRD.CalibPIDrefMaker", mgr->GetCommonFileName())));
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestTDx.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// This test covers the 3DConnexion device interface.
//
// The command line arguments are:
// -I        => run in interactive mode; unless this is used, the program will
//              not allow interaction and exit

#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"

#include "vtkRenderWindowInteractor.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkActor.h"

#include "vtkPolyDataMapper.h"
#include "vtkCamera.h"

#include "vtkConeSource.h"
#include "vtkProperty.h"
#include "vtkTDxMotionEventInfo.h"
#include "vtkCommand.h"

class myCommand : public vtkCommand
{
public:
  myCommand()
    {
      this->Camera=0;
    }
  void Execute(vtkObject *caller, unsigned long eventId,
               void *callData)
    {
      cout << "myCommand::Execute()" << endl;
      if(eventId==vtkCommand::TDxMotionEvent)
        {
        vtkTDxMotionEventInfo *i=
          static_cast<vtkTDxMotionEventInfo *>(callData);

        cout << "x=" << i->X << " y=" << i->Y << " z=" << i->Z
             << " a=" << i->A << " b=" << i->B << " c=" << i->C << endl;

        const double sensitivity=0.02;

        this->Camera->Roll(i->B*sensitivity);
        this->RenderWindowInteractor->Render();
        }
      else
        {
        cout << "unexpected VTK event" << endl;
        }
    }
  void SetCamera(vtkCamera *c)
    {
      this->Camera=c;
    }

  void SetRenderWindowInteractor(vtkRenderWindowInteractor *i)
    {
      this->RenderWindowInteractor=i;
    }

protected:
  vtkCamera *Camera;
  vtkRenderWindowInteractor *RenderWindowInteractor;

};

int TestTDx(int argc, char* argv[])
{
  vtkRenderWindowInteractor *iren=vtkRenderWindowInteractor::New();
  iren->SetUseTDx(true);
  vtkRenderWindow *renWin = vtkRenderWindow::New();
  renWin->SetMultiSamples(0);

  renWin->SetAlphaBitPlanes(1);
  iren->SetRenderWindow(renWin);
  renWin->Delete();

  vtkRenderer *renderer = vtkRenderer::New();
  renWin->AddRenderer(renderer);
  renderer->Delete();

  vtkConeSource *coneSource1=vtkConeSource::New();
  vtkPolyDataMapper *coneMapper1=vtkPolyDataMapper::New();
  coneMapper1->SetInputConnection(coneSource1->GetOutputPort());
  coneSource1->Delete();
  vtkActor *coneActor1=vtkActor::New();
  coneActor1->SetMapper(coneMapper1);
  coneMapper1->Delete();
  coneActor1->SetPosition(-2.0,0.0,0.0);
  renderer->AddActor(coneActor1);
  coneActor1->Delete();

  vtkConeSource *coneSource2=vtkConeSource::New();
  vtkPolyDataMapper *coneMapper2=vtkPolyDataMapper::New();
  coneMapper2->SetInputConnection(coneSource2->GetOutputPort());
  coneSource2->Delete();
  vtkActor *coneActor2=vtkActor::New();
  coneActor2->SetMapper(coneMapper2);
  coneMapper2->Delete();
  coneActor2->SetPosition(0.0,0.0,0.0);
  coneActor2->GetProperty()->SetLighting(false);
  renderer->AddActor(coneActor2);
  coneActor2->Delete();

  vtkConeSource *coneSource3=vtkConeSource::New();
  vtkPolyDataMapper *coneMapper3=vtkPolyDataMapper::New();
  coneMapper3->SetInputConnection(coneSource3->GetOutputPort());
  coneSource3->Delete();
  vtkActor *coneActor3=vtkActor::New();
  coneActor3->SetMapper(coneMapper3);
  coneMapper3->Delete();
  coneActor3->SetPosition(2.0,0.0,0.0);
  renderer->AddActor(coneActor3);
  coneActor3->Delete();

  renderer->SetBackground(0.1,0.3,0.0);
  renWin->SetSize(200,200);

  renWin->Render();

  vtkCamera *camera=renderer->GetActiveCamera();
  camera->Azimuth(-40.0);
  camera->Elevation(20.0);
  renderer->ResetCamera();
  renWin->Render();

  myCommand *c=new myCommand;
  c->Register(0);
  c->SetCamera(camera);
  c->SetRenderWindowInteractor(iren);

  iren->AddObserver(vtkCommand::TDxMotionEvent,c,0);

  int retVal = vtkRegressionTestImage( renWin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }
  iren->Delete();

  c->Delete();
  c->Delete();

  return !retVal;
}
<commit_msg>COMP:Fixed warning.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestTDx.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// This test covers the 3DConnexion device interface.
//
// The command line arguments are:
// -I        => run in interactive mode; unless this is used, the program will
//              not allow interaction and exit

#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"

#include "vtkRenderWindowInteractor.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkActor.h"

#include "vtkPolyDataMapper.h"
#include "vtkCamera.h"

#include "vtkConeSource.h"
#include "vtkProperty.h"
#include "vtkTDxMotionEventInfo.h"
#include "vtkCommand.h"

class myCommand : public vtkCommand
{
public:
  myCommand()
    {
      this->Camera=0;
    }
  void Execute(vtkObject *caller, unsigned long eventId,
               void *vtkNotUsed(callData))
    {
      cout << "myCommand::Execute()" << endl;
      if(eventId==vtkCommand::TDxMotionEvent)
        {
        vtkTDxMotionEventInfo *i=
          static_cast<vtkTDxMotionEventInfo *>(callData);

        cout << "x=" << i->X << " y=" << i->Y << " z=" << i->Z
             << " a=" << i->A << " b=" << i->B << " c=" << i->C << endl;

        const double sensitivity=0.02;

        this->Camera->Roll(i->B*sensitivity);
        this->RenderWindowInteractor->Render();
        }
      else
        {
        cout << "unexpected VTK event" << endl;
        }
    }
  void SetCamera(vtkCamera *c)
    {
      this->Camera=c;
    }

  void SetRenderWindowInteractor(vtkRenderWindowInteractor *i)
    {
      this->RenderWindowInteractor=i;
    }

protected:
  vtkCamera *Camera;
  vtkRenderWindowInteractor *RenderWindowInteractor;

};

int TestTDx(int argc, char* argv[])
{
  vtkRenderWindowInteractor *iren=vtkRenderWindowInteractor::New();
  iren->SetUseTDx(true);
  vtkRenderWindow *renWin = vtkRenderWindow::New();
  renWin->SetMultiSamples(0);

  renWin->SetAlphaBitPlanes(1);
  iren->SetRenderWindow(renWin);
  renWin->Delete();

  vtkRenderer *renderer = vtkRenderer::New();
  renWin->AddRenderer(renderer);
  renderer->Delete();

  vtkConeSource *coneSource1=vtkConeSource::New();
  vtkPolyDataMapper *coneMapper1=vtkPolyDataMapper::New();
  coneMapper1->SetInputConnection(coneSource1->GetOutputPort());
  coneSource1->Delete();
  vtkActor *coneActor1=vtkActor::New();
  coneActor1->SetMapper(coneMapper1);
  coneMapper1->Delete();
  coneActor1->SetPosition(-2.0,0.0,0.0);
  renderer->AddActor(coneActor1);
  coneActor1->Delete();

  vtkConeSource *coneSource2=vtkConeSource::New();
  vtkPolyDataMapper *coneMapper2=vtkPolyDataMapper::New();
  coneMapper2->SetInputConnection(coneSource2->GetOutputPort());
  coneSource2->Delete();
  vtkActor *coneActor2=vtkActor::New();
  coneActor2->SetMapper(coneMapper2);
  coneMapper2->Delete();
  coneActor2->SetPosition(0.0,0.0,0.0);
  coneActor2->GetProperty()->SetLighting(false);
  renderer->AddActor(coneActor2);
  coneActor2->Delete();

  vtkConeSource *coneSource3=vtkConeSource::New();
  vtkPolyDataMapper *coneMapper3=vtkPolyDataMapper::New();
  coneMapper3->SetInputConnection(coneSource3->GetOutputPort());
  coneSource3->Delete();
  vtkActor *coneActor3=vtkActor::New();
  coneActor3->SetMapper(coneMapper3);
  coneMapper3->Delete();
  coneActor3->SetPosition(2.0,0.0,0.0);
  renderer->AddActor(coneActor3);
  coneActor3->Delete();

  renderer->SetBackground(0.1,0.3,0.0);
  renWin->SetSize(200,200);

  renWin->Render();

  vtkCamera *camera=renderer->GetActiveCamera();
  camera->Azimuth(-40.0);
  camera->Elevation(20.0);
  renderer->ResetCamera();
  renWin->Render();

  myCommand *c=new myCommand;
  c->Register(0);
  c->SetCamera(camera);
  c->SetRenderWindowInteractor(iren);

  iren->AddObserver(vtkCommand::TDxMotionEvent,c,0);

  int retVal = vtkRegressionTestImage( renWin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }
  iren->Delete();

  c->Delete();
  c->Delete();

  return !retVal;
}
<|endoftext|>


<commit_before>/*
TLD's work well w/ features (keypts) low-level features

- DoT works well with textureless objects (contoures)
- Use both to bootstrap a contour and features based reconstruction
- Does going to 3D from contour make tracking possible ??

*/
#define WINDOW_NAME "TLD Segmenter"

#include <set>
#include <bot_core/bot_core.h>
#include <bot_frames/bot_frames.h>
#include <bot_param/param_client.h>

#include <opencv2/opencv.hpp>

#include <image_io_utils/image_io_utils.hpp> // to simplify jpeg/zlib compression and decompression
#include <lcmtypes/perception_image_roi_t.h>
#include <ConciseArgs>

const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 800;

int MAX_IMAGE_WIDTH = 0;
int MAX_IMAGE_HEIGHT = 0;

int32_t OBJECT_ID = 1;
int32_t FEATURE_ID = 1; // 1 for object (reference), -1 for virtual heading object
using namespace cv;

struct state_t {
    lcm_t *lcm;
    GMainLoop *mainloop;
    BotParam *param;
    BotFrames *frames;
    int counter;

    // Img
    cv::Mat img;

    // utimes for image
    int64_t  img_utime;

    // UI selection of desired object
    Rect selection, selection_virtual;
    Point origin, origin_virtual;
    bool selectObject, selectObject_virtual;

    state_t () {
        // LCM, BotFrames, BotParam inits
        lcm =  bot_lcm_get_global(NULL);
        param = bot_param_new_from_server(lcm, 1);
        frames = bot_frames_get_global (lcm, param);

        // Counter for debug prints
        counter = 0;

        selectObject = false;
        selectObject_virtual = false;
    }
    ~state_t () {
        lcm_destroy(lcm);
    }

};
state_t * state = NULL;

struct MouseEvent {
    MouseEvent() { event = -1; buttonState = 0; }
    Point pt;
    int event;
    int buttonState;
};
MouseEvent mouse;

static void onMouse(int event, int x, int y, int flags, void* userdata) {
    MouseEvent* data = (MouseEvent*)userdata;

    float sx = 1.f / WINDOW_WIDTH ;
    float sy = 1.f / WINDOW_HEIGHT;

    if (state->selectObject) {
        state->selection.x = MIN(x, state->origin.x);
        state->selection.y = MIN(y, state->origin.y);
        state->selection.width = std::abs(x - state->origin.x);
        state->selection.height = std::abs(y - state->origin.y);
        state->selection &= Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
    }

    if (state->selectObject_virtual) {
        state->selection_virtual.x = MIN(x, state->origin_virtual.x);
        state->selection_virtual.y = MIN(y, state->origin_virtual.y);
        state->selection_virtual.width = std::abs(x - state->origin_virtual.x);
        state->selection_virtual.height = std::abs(y - state->origin_virtual.y);
        state->selection &= Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
    }

    switch (event) {
    case CV_EVENT_RBUTTONDOWN:
        state->origin_virtual = Point(x, y);
        state->selection_virtual = Rect(x, y, 0, 0);
        state->selectObject_virtual = true;
        break;
    case CV_EVENT_RBUTTONUP:
        state->selectObject_virtual = false;
        std::cerr << "SEND virtual selection: " << state->img_utime << " - " <<
            state->selection_virtual.x << " " << state->selection_virtual.y << " " <<
            state->selection_virtual.width << " " << state->selection_virtual.height << std::endl;

        perception_image_roi_t img_vselection;
        img_vselection.utime = state->img_utime;
        img_vselection.object_id = OBJECT_ID;
        img_vselection.feature_id = -1; // FEATURE_ID;
        img_vselection.roi.x = state->selection_virtual.x * sx;
        img_vselection.roi.y = state->selection_virtual.y * sy;
        img_vselection.roi.width = state->selection_virtual.width * sx;
        img_vselection.roi.height = state->selection_virtual.height * sy;
        perception_image_roi_t_publish(state->lcm, "TLD_OBJECT_ROI", &img_vselection);

        destroyWindow(WINDOW_NAME);
        state->img = cv::Mat();

        break;
    case CV_EVENT_LBUTTONDOWN:
        state->origin = Point(x, y);
        state->selection = Rect(x, y, 0, 0);
        state->selectObject = true;

        // reset virtual feature
        state->selection_virtual = Rect(0,0,0,0);

        break;
    case CV_EVENT_LBUTTONUP:
        state->selectObject = false;
        std::cerr << "SEND selection: " << state->img_utime << " - " <<
            state->selection.x << " " << state->selection.y << " " <<
            state->selection.width << " " << state->selection.height << std::endl;

        perception_image_roi_t img_selection;
        img_selection.utime = state->img_utime;
        img_selection.object_id = OBJECT_ID;
        img_selection.feature_id = 1; // FEATURE_ID;
        img_selection.roi.x = state->selection.x * sx;
        img_selection.roi.y = state->selection.y * sy;
        img_selection.roi.width = state->selection.width * sx;
        img_selection.roi.height = state->selection.height * sy;
        perception_image_roi_t_publish(state->lcm, "TLD_OBJECT_ROI", &img_selection);
        // destroyWindow(WINDOW_NAME);
        // state->img = cv::Mat();

        break;
    }
    return;
}

void  INThandler(int sig)
{
    printf("Exiting\n");
    if (state) delete state;
    exit(0);
}

void
decode_image(const bot_core_image_t * msg, cv::Mat& img)
{
    int ch = msg->row_stride / (msg->width);
    if (img.empty() || img.rows != msg->height || img.cols != msg->width)
        if (ch == 3)
            img.create(msg->height, msg->width, CV_8UC3);
        else
            img.create(msg->height, msg->width, CV_8UC1);
    std::cerr << "msg: " << ch << " " << msg->row_stride << " " << msg->width << "x" << msg->height << std::endl;

  // extract image data
  switch (msg->pixelformat) {
    case BOT_CORE_IMAGE_T_PIXEL_FORMAT_RGB:
        memcpy(img.data, msg->data, sizeof(uint8_t) * msg->width * msg->height * 3);
        cv::cvtColor(img, img, CV_RGB2BGR);
      break;
    case BOT_CORE_IMAGE_T_PIXEL_FORMAT_MJPEG:
      // for some reason msg->row_stride is 0, so we use msg->width instead.
        if (ch == 3) {
            jpeg_decompress_8u_rgb(msg->data,
                                    msg->size,
                                    img.data,
                                    msg->width,
                                    msg->height,
                                    msg->width * ch);
        cv::cvtColor(img, img, CV_RGB2BGR);
        } else {
            jpeg_decompress_8u_gray(msg->data,
                                    msg->size,
                                    img.data,
                                    msg->width,
                                    msg->height,
                                    msg->width);
        }
      break;
  case BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY:
      memcpy(img.data, msg->data, sizeof(uint8_t) * msg->width * msg->height);
      break;
    default:
      fprintf(stderr, "Unrecognized image format\n");
      break;
  }
  return;
}

static void on_image_frame (const lcm_recv_buf_t *rbuf, const char *channel,
                            const bot_core_image_t *msg,
                            void *user_data ) {

    if (!msg->width || !msg->height) return;

    if (!MAX_IMAGE_WIDTH || !MAX_IMAGE_HEIGHT) {
        MAX_IMAGE_WIDTH = msg->width;
        MAX_IMAGE_HEIGHT = msg->height;
    }

    state_t* state = (state_t*) user_data;
    if (state->img.empty() || state->img.rows != msg->height || state->img.cols != msg->width) {
        if (msg->pixelformat == BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY) {
            std::cerr << "ERROR: Incoming image is grayscale!! Cannot perform color tracking!!!" << std::endl;
            assert(0);
        } else {
            std::cerr << "One time creation of image" << std::endl;
            state->img.create(msg->height, msg->width, CV_8UC3);
        }
    }
    decode_image(msg, state->img);
    state->img_utime = msg->utime;

    cv::namedWindow( WINDOW_NAME );
    cv::setMouseCallback( WINDOW_NAME, onMouse, &mouse);
    state->selectObject_virtual = false;
    state->selectObject = false;

    return;
}

struct TLDSegmenterOptions {
    bool vDEBUG;
    std::string vCHANNEL;

    TLDSegmenterOptions () :
        vCHANNEL(std::string("CAMERALEFT")), vDEBUG(false) {}
};
TLDSegmenterOptions options;

int main(int argc, char** argv)
{
    std::cout << "============= QUICK MODES ===================\n";
    std::cout << "drc-tld-segmenter -c CAMERALEFT\n";
    std::cout << "=============================================\n";

    ConciseArgs opt(argc, (char**)argv);
    opt.add(options.vCHANNEL, "c", "camera-channel","Camera Channel [CAMERALEFT]");
    opt.add(options.vDEBUG, "d", "debug","Debug mode");
    opt.parse();

    std::cerr << "===========  TLD Tracker ============" << std::endl;
    std::cerr << "=> CAMERA CHANNEL : " << options.vCHANNEL << std::endl;
    std::cerr << "=> DEBUG : " << options.vDEBUG << std::endl;
    std::cerr << "===============================================" << std::endl;

    // Install signal handler to free data.
    signal(SIGINT, INThandler);

    // Param server, botframes
    state = new state_t();

    // cv::namedWindow( WINDOW_NAME );
    // cv::setMouseCallback( WINDOW_NAME, onMouse, &mouse);

    // Subscriptions
    bot_core_image_t_subscribe(state->lcm, options.vCHANNEL.c_str(), on_image_frame, (void*)state);

    // Install signal handler to free data.
    signal(SIGINT, INThandler);

    while(1) {
        unsigned char c = cv::waitKey(1) & 0xff;
	lcm_handle(state->lcm);
        if (c == 'q') {
            break;
        // } else if (c == 'd') {
        //     FEATURE_ID++;
        // } else if (c == 'a') {
        //     FEATURE_ID--;
        } else if (c == 'w') {
            OBJECT_ID++;
        } else if (c == 's') {
            OBJECT_ID--;
        }

        // UI handling
        if (!state->img.empty()) {
            cv::Mat display;
            cv::resize(state->img.clone(), display, cv::Size(WINDOW_WIDTH,WINDOW_HEIGHT));
            if (state->selection.width > 0 && state->selection.height > 0) {

                cv::Mat roi(display, state->selection);
                rectangle(display, state->selection, cv::Scalar(0,255,255), 2);
                // bitwise_not(roi, roi);
            }
            if (state->selection_virtual.width > 0 && state->selection_virtual.height > 0) {

                cv::Mat roi(display, state->selection_virtual);
                rectangle(display, state->selection_virtual, cv::Scalar(0,255,0), 2);
                // bitwise_not(roi, roi);
            }

            // Show OBJECT_ID, FEATURE_ID
            cv::putText(display, cv::format("OBJ: %ld", OBJECT_ID),
                        Point(20,20), 0, .5, cv::Scalar(0,200,0), 2);

            imshow(WINDOW_NAME, display);
        }
    }

    if (state) delete state;
    return 0;
}
<commit_msg>modified tld-segmenter to work with live stream<commit_after>/*
TLD's work well w/ features (keypts) low-level features

- DoT works well with textureless objects (contoures)
- Use both to bootstrap a contour and features based reconstruction
- Does going to 3D from contour make tracking possible ??

*/
#define WINDOW_NAME "TLD Segmenter"

#include <set>
#include <bot_core/bot_core.h>
#include <bot_frames/bot_frames.h>
#include <bot_param/param_client.h>

#include <opencv2/opencv.hpp>

#include <image_io_utils/image_io_utils.hpp> // to simplify jpeg/zlib compression and decompression
#include <lcmtypes/perception_image_roi_t.h>
#include <ConciseArgs>

const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 800;

int MAX_IMAGE_WIDTH = 0;
int MAX_IMAGE_HEIGHT = 0;

int32_t OBJECT_ID = 1;
int32_t FEATURE_ID = 1; // 1 for object (reference), -1 for virtual heading object
using namespace cv;

struct state_t {
    lcm_t *lcm;
    GMainLoop *mainloop;
    BotParam *param;
    BotFrames *frames;
    int counter;

    // Img
    cv::Mat img;

    // utimes for image
    int64_t  img_utime;

    // UI selection of desired object
    Rect selection, selection_virtual;
    Point origin, origin_virtual;
    bool selectObject, selectObject_virtual;

    state_t () {
        // LCM, BotFrames, BotParam inits
        lcm =  bot_lcm_get_global(NULL);
        param = bot_param_new_from_server(lcm, 1);
        frames = bot_frames_get_global (lcm, param);

        // Counter for debug prints
        counter = 0;

        selectObject = false;
        selectObject_virtual = false;
    }
    ~state_t () {
        lcm_destroy(lcm);
    }

};
state_t * state = NULL;

struct MouseEvent {
    MouseEvent() { event = -1; buttonState = 0; }
    Point pt;
    int event;
    int buttonState;
};
MouseEvent mouse;

static void onMouse(int event, int x, int y, int flags, void* userdata) {
    MouseEvent* data = (MouseEvent*)userdata;

    float sx = 1.f / WINDOW_WIDTH ;
    float sy = 1.f / WINDOW_HEIGHT;

    if (state->selectObject) {
        state->selection.x = MIN(x, state->origin.x);
        state->selection.y = MIN(y, state->origin.y);
        state->selection.width = std::abs(x - state->origin.x);
        state->selection.height = std::abs(y - state->origin.y);
        state->selection &= Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
    }

    if (state->selectObject_virtual) {
        state->selection_virtual.x = MIN(x, state->origin_virtual.x);
        state->selection_virtual.y = MIN(y, state->origin_virtual.y);
        state->selection_virtual.width = std::abs(x - state->origin_virtual.x);
        state->selection_virtual.height = std::abs(y - state->origin_virtual.y);
        state->selection &= Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
    }

    switch (event) {
    case CV_EVENT_RBUTTONDOWN:
        state->origin_virtual = Point(x, y);
        state->selection_virtual = Rect(x, y, 0, 0);
        state->selectObject_virtual = true;
        break;
    case CV_EVENT_RBUTTONUP:
        state->selectObject_virtual = false;
        std::cerr << "SEND virtual selection: " << state->img_utime << " - " <<
            state->selection_virtual.x << " " << state->selection_virtual.y << " " <<
            state->selection_virtual.width << " " << state->selection_virtual.height << std::endl;

        perception_image_roi_t img_vselection;
        img_vselection.utime = state->img_utime;
        img_vselection.object_id = OBJECT_ID;
        img_vselection.feature_id = -1; // FEATURE_ID;
        img_vselection.roi.x = state->selection_virtual.x * sx;
        img_vselection.roi.y = state->selection_virtual.y * sy;
        img_vselection.roi.width = state->selection_virtual.width * sx;
        img_vselection.roi.height = state->selection_virtual.height * sy;
        perception_image_roi_t_publish(state->lcm, "TLD_OBJECT_ROI", &img_vselection);

        // destroyWindow(WINDOW_NAME);
        // state->img = cv::Mat();

        break;
    case CV_EVENT_LBUTTONDOWN:
        state->origin = Point(x, y);
        state->selection = Rect(x, y, 0, 0);
        state->selectObject = true;

        // reset virtual feature
        state->selection_virtual = Rect(0,0,0,0);

        break;
    case CV_EVENT_LBUTTONUP:
        state->selectObject = false;
        std::cerr << "SEND selection: " << state->img_utime << " - " <<
            state->selection.x << " " << state->selection.y << " " <<
            state->selection.width << " " << state->selection.height << std::endl;

        perception_image_roi_t img_selection;
        img_selection.utime = state->img_utime;
        img_selection.object_id = OBJECT_ID;
        img_selection.feature_id = 1; // FEATURE_ID;
        img_selection.roi.x = state->selection.x * sx;
        img_selection.roi.y = state->selection.y * sy;
        img_selection.roi.width = state->selection.width * sx;
        img_selection.roi.height = state->selection.height * sy;
        perception_image_roi_t_publish(state->lcm, "TLD_OBJECT_ROI", &img_selection);
        // destroyWindow(WINDOW_NAME);
        // state->img = cv::Mat();

        break;
    }
    return;
}

void  INThandler(int sig)
{
    printf("Exiting\n");
    if (state) delete state;
    exit(0);
}

void
decode_image(const bot_core_image_t * msg, cv::Mat& img)
{
    int ch = msg->row_stride / (msg->width);
    if (img.empty() || img.rows != msg->height || img.cols != msg->width)
        if (ch == 3)
            img.create(msg->height, msg->width, CV_8UC3);
        else
            img.create(msg->height, msg->width, CV_8UC1);
    std::cerr << "msg: " << ch << " " << msg->row_stride << " " << msg->width << "x" << msg->height << std::endl;

  // extract image data
  switch (msg->pixelformat) {
    case BOT_CORE_IMAGE_T_PIXEL_FORMAT_RGB:
        memcpy(img.data, msg->data, sizeof(uint8_t) * msg->width * msg->height * 3);
        cv::cvtColor(img, img, CV_RGB2BGR);
      break;
    case BOT_CORE_IMAGE_T_PIXEL_FORMAT_MJPEG:
      // for some reason msg->row_stride is 0, so we use msg->width instead.
        if (ch == 3) {
            jpeg_decompress_8u_rgb(msg->data,
                                    msg->size,
                                    img.data,
                                    msg->width,
                                    msg->height,
                                    msg->width * ch);
        cv::cvtColor(img, img, CV_RGB2BGR);
        } else {
            jpeg_decompress_8u_gray(msg->data,
                                    msg->size,
                                    img.data,
                                    msg->width,
                                    msg->height,
                                    msg->width);
        }
      break;
  case BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY:
      memcpy(img.data, msg->data, sizeof(uint8_t) * msg->width * msg->height);
      break;
    default:
      fprintf(stderr, "Unrecognized image format\n");
      break;
  }
  return;
}

static void on_image_frame (const lcm_recv_buf_t *rbuf, const char *channel,
                            const bot_core_image_t *msg,
                            void *user_data ) {

    if (!msg->width || !msg->height) return;

    if (!MAX_IMAGE_WIDTH || !MAX_IMAGE_HEIGHT) {
        MAX_IMAGE_WIDTH = msg->width;
        MAX_IMAGE_HEIGHT = msg->height;
    }

    state_t* state = (state_t*) user_data;
    if (state->img.empty() || state->img.rows != msg->height || state->img.cols != msg->width) {
        if (msg->pixelformat == BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY) {
            std::cerr << "ERROR: Incoming image is grayscale!! Cannot perform color tracking!!!" << std::endl;
            assert(0);
        } else {
            std::cerr << "One time creation of image" << std::endl;
            state->img.create(msg->height, msg->width, CV_8UC3);
        }
    }
    decode_image(msg, state->img);
    state->img_utime = msg->utime;
    return;
}

struct TLDSegmenterOptions {
    bool vDEBUG;
    std::string vCHANNEL;

    TLDSegmenterOptions () :
        vCHANNEL(std::string("CAMERALEFT")), vDEBUG(false) {}
};
TLDSegmenterOptions options;

int main(int argc, char** argv)
{
    std::cout << "============= QUICK MODES ===================\n";
    std::cout << "drc-tld-segmenter -c CAMERALEFT\n";
    std::cout << "=============================================\n";

    ConciseArgs opt(argc, (char**)argv);
    opt.add(options.vCHANNEL, "c", "camera-channel","Camera Channel [CAMERALEFT]");
    opt.add(options.vDEBUG, "d", "debug","Debug mode");
    opt.parse();

    std::cerr << "===========  TLD Tracker ============" << std::endl;
    std::cerr << "=> CAMERA CHANNEL : " << options.vCHANNEL << std::endl;
    std::cerr << "=> DEBUG : " << options.vDEBUG << std::endl;
    std::cerr << "===============================================" << std::endl;

    // Install signal handler to free data.
    signal(SIGINT, INThandler);

    // Param server, botframes
    state = new state_t();

    cv::namedWindow( WINDOW_NAME );
    cv::setMouseCallback( WINDOW_NAME, onMouse, &mouse);

    // Subscriptions
    bot_core_image_t_subscribe(state->lcm, options.vCHANNEL.c_str(), on_image_frame, (void*)state);

    // Install signal handler to free data.
    signal(SIGINT, INThandler);

    while(1) {
        unsigned char c = cv::waitKey(1) & 0xff;
	lcm_handle(state->lcm);
        if (c == 'q') {
            break;
        // } else if (c == 'd') {
        //     FEATURE_ID++;
        // } else if (c == 'a') {
        //     FEATURE_ID--;
        } else if (c == 'w') {
            OBJECT_ID++;
        } else if (c == 's') {
            OBJECT_ID--;
        }

        // UI handling
        if (!state->img.empty()) {
            cv::Mat display;
            cv::resize(state->img.clone(), display, cv::Size(WINDOW_WIDTH,WINDOW_HEIGHT));
            if (state->selection.width > 0 && state->selection.height > 0) {

                cv::Mat roi(display, state->selection);
                rectangle(display, state->selection, cv::Scalar(0,255,255), 2);
                // bitwise_not(roi, roi);
            }
            if (state->selection_virtual.width > 0 && state->selection_virtual.height > 0) {

                cv::Mat roi(display, state->selection_virtual);
                rectangle(display, state->selection_virtual, cv::Scalar(0,255,0), 2);
                // bitwise_not(roi, roi);
            }

            // Show OBJECT_ID, FEATURE_ID
            cv::putText(display, cv::format("OBJ: %ld", OBJECT_ID),
                        Point(20,20), 0, .5, cv::Scalar(0,200,0), 2);

            imshow(WINDOW_NAME, display);
        }
    }

    if (state) delete state;
    return 0;
}
<|endoftext|>


<commit_before>
/////////////////////////////////////////////////////////////////////////////
// Copyright (c) 1996, California Institute of Technology.
// ALL RIGHTS RESERVED.   U.S. Government Sponsorship acknowledged.
//
// Please read the full copyright notice in the file COPYRIGH
// in this directory.
//
// Author: Todd Karakashian, NASA/Jet Propulsion Laboratory
//         Todd.K.Karakashian@jpl.nasa.gov
//
// $RCSfile: escaping.cc,v $ - Miscellaneous routines for DODS HDF server
//
// $Log: escaping.cc,v $
// Revision 1.2  1997/02/14 02:18:16  jimg
// Added to DODS core
//
// Revision 1.2  1996/10/07 21:15:17  todd
// Changes escape character to % from _.
//
// Revision 1.1  1996/09/24 22:38:16  todd
// Initial revision
//
//
/////////////////////////////////////////////////////////////////////////////

// These two routines are for escaping/unescaping strings that are identifiers
// in DODS
// id2dods() -- escape (using WWW hex codes) non-allowable characters in a
// DODS identifier
// dods2id() -- given an WWW hexcode escaped identifier, restore it
//
// These two routines are for escaping/unescaping strings storing attribute
// values.  They use traditional octal escapes (\nnn) because they are
// intended to be viewed by a user
// escattr() -- escape (using traditional octal backslash) non-allowable
// characters in the value of a DODS attribute
// unescattr() -- given an octally escaped string, restore it
//
// These are routines used by the above, not intended to be called directly:
//
// hexstring()
// unhexstring()
// octstring()
// unoctstring()
//
// -Todd

#include <strstream.h>
#include <iomanip.h>
#include <String.h>
#include <mfhdf.h>
#include <hdfclass.h>
#include "HDFStructure.h"
#include "HDFArray.h"
#include "hdfutil.h"
#include "dhdferr.h"

String hexstring(int val) {
    static char buf[hdfclass::MAXSTR];

    ostrstream(buf,hdfclass::MAXSTR) << hex << setw(2) << setfill('0') <<
	val << ends;

    return (String)buf;
}

char unhexstring(String s) {
    int val;
    static char buf[hdfclass::MAXSTR];

    strcpy(buf,(const char *)s);
    istrstream(buf,hdfclass::MAXSTR) >> hex >> val;

    return (char)val;
}

String octstring(int val) {
    static char buf[hdfclass::MAXSTR];

    ostrstream(buf,hdfclass::MAXSTR) << oct << setw(3) << setfill('0') <<
	val << ends;

    return (String)buf;
}

char unoctstring(String s) {
    int val;
    static char buf[hdfclass::MAXSTR];

    strcpy(buf,(const char *)s);
    istrstream(buf,hdfclass::MAXSTR) >> oct >> val;

    return (char)val;
}

// replace characters that are not allowed in DODS identifiers
String id2dods(String s) {
    static Regex badregx = "[^0-9a-zA-Z_%]";
    const char ESC = '%';

    int index;
    while ( (index = s.index(badregx)) >= 0)
	s.at(index,1) = ESC + hexstring(toascii(s[index]));
    if (isdigit(s[0]))
	s.before(0) = '_';
    return s;
}

String dods2id(String s) {
    static Regex escregx = "%[0-7][0-9a-fA-F]";

    int index;
    while ( (index = s.index(escregx)) >= 0)
	s.at(index,3) = unhexstring(s.at(index+1,2));

    return s;
}

// Escape non-printable characters and quotes from an HDF attribute
String escattr(String s) {
    static Regex nonprintable = "[^ !-~]";
    const char ESC = '\\';
    const char QUOTE = '\"';
    const String ESCQUOTE = (String)ESC + (String)QUOTE;

    // escape non-printing characters with octal escape
    int index = 0;
    while ( (index = s.index(nonprintable)) >= 0)
	s.at(index,1) = ESC + octstring(toascii(s[index]));

    // escape " with backslash
    index = 0;
    while ( (index = s.index(QUOTE,index)) >= 0) {
	s.at(index,1) = ESCQUOTE;
	index += ESCQUOTE.length();
    }

    return s;
}

// Un-escape special characters, quotes and backslashes from an HDF attribute.
// Note: A regex to match one \ must be defined as
//          Regex foo = "\\\\";
//       because both C++ strings and libg++ regex's also employ \ as
//       an escape character!
String unescattr(String s) {
    static Regex escregx = "\\\\[01][0-7][0-7]";  // matches 4 characters
    static Regex escquoteregex = "[^\\\\]\\\\\"";  // matches 3 characters
    static Regex escescregex = "\\\\\\\\";      // matches 2 characters
    const char ESC = '\\';
    const char QUOTE = '\"';
    const String ESCQUOTE = (String)ESC + (String)QUOTE;

    // unescape any octal-escaped ASCII characters
    int index = 0;
    while ( (index = s.index(escregx,index)) >= 0) {
	s.at(index,4) = unoctstring(s.at(index+1,3));
	index++;
    }

    // unescape any escaped quotes
    index = 0;
    while ( (index = s.index(escquoteregex,index)) >= 0) {
	s.at(index+1,2) = QUOTE;
	index++;
    }

    // unescape any escaped backslashes
    index = 0;
    while ( (index = s.index(escescregex,index)) >= 0) {
	s.at(index,2) = ESC;
	index++;
    }

    return s;
}
<commit_msg>Removed reliance on the dods-hdf code. Introduced a const int MAXSTR with value 256. This matches the length of ID_MAX in the parser.h header (which I did not include since it defines a lot of software that is irrelevant to this module).<commit_after>
/////////////////////////////////////////////////////////////////////////////
// Copyright (c) 1996, California Institute of Technology.
// ALL RIGHTS RESERVED.   U.S. Government Sponsorship acknowledged.
//
// Please read the full copyright notice in the file COPYRIGH
// in this directory.
//
// Author: Todd Karakashian, NASA/Jet Propulsion Laboratory
//         Todd.K.Karakashian@jpl.nasa.gov
//
// $RCSfile: escaping.cc,v $ - Miscellaneous routines for DODS HDF server
//
// $Log: escaping.cc,v $
// Revision 1.3  1997/02/14 02:24:44  jimg
// Removed reliance on the dods-hdf code.
// Introduced a const int MAXSTR with value 256. This matches the length of
// ID_MAX in the parser.h header (which I did not include since it defines
// a lot of software that is irrelevant to this module).
//
// Revision 1.2  1997/02/14 02:18:16  jimg
// Added to DODS core
//
// Revision 1.2  1996/10/07 21:15:17  todd
// Changes escape character to % from _.
//
// Revision 1.1  1996/09/24 22:38:16  todd
// Initial revision
//
//
/////////////////////////////////////////////////////////////////////////////

// These two routines are for escaping/unescaping strings that are identifiers
// in DODS
// id2dods() -- escape (using WWW hex codes) non-allowable characters in a
// DODS identifier
// dods2id() -- given an WWW hexcode escaped identifier, restore it
//
// These two routines are for escaping/unescaping strings storing attribute
// values.  They use traditional octal escapes (\nnn) because they are
// intended to be viewed by a user
// escattr() -- escape (using traditional octal backslash) non-allowable
// characters in the value of a DODS attribute
// unescattr() -- given an octally escaped string, restore it
//
// These are routines used by the above, not intended to be called directly:
//
// hexstring()
// unhexstring()
// octstring()
// unoctstring()
//
// -Todd

#include <ctype.h>
#include <strstream.h>
#include <iomanip.h>
#include <String.h>

#if 0
#include <mfhdf.h>
#include <hdfclass.h>
#include "HDFStructure.h"
#include "HDFArray.h"
#include "hdfutil.h"
#include "dhdferr.h"
#endif

const int MAXSTR = 256;

String hexstring(int val) {
    static char buf[MAXSTR];

    ostrstream(buf,MAXSTR) << hex << setw(2) << setfill('0') <<
	val << ends;

    return (String)buf;
}

char unhexstring(String s) {
    int val;
    static char buf[MAXSTR];

    strcpy(buf,(const char *)s);
    istrstream(buf,MAXSTR) >> hex >> val;

    return (char)val;
}

String octstring(int val) {
    static char buf[MAXSTR];

    ostrstream(buf,MAXSTR) << oct << setw(3) << setfill('0') <<
	val << ends;

    return (String)buf;
}

char unoctstring(String s) {
    int val;
    static char buf[MAXSTR];

    strcpy(buf,(const char *)s);
    istrstream(buf,MAXSTR) >> oct >> val;

    return (char)val;
}

// replace characters that are not allowed in DODS identifiers
String id2dods(String s) {
    static Regex badregx = "[^0-9a-zA-Z_%]";
    const char ESC = '%';

    int index;
    while ( (index = s.index(badregx)) >= 0)
	s.at(index,1) = ESC + hexstring(toascii(s[index]));
    if (isdigit(s[0]))
	s.before(0) = '_';
    return s;
}

String dods2id(String s) {
    static Regex escregx = "%[0-7][0-9a-fA-F]";

    int index;
    while ( (index = s.index(escregx)) >= 0)
	s.at(index,3) = unhexstring(s.at(index+1,2));

    return s;
}

// Escape non-printable characters and quotes from an HDF attribute
String escattr(String s) {
    static Regex nonprintable = "[^ !-~]";
    const char ESC = '\\';
    const char QUOTE = '\"';
    const String ESCQUOTE = (String)ESC + (String)QUOTE;

    // escape non-printing characters with octal escape
    int index = 0;
    while ( (index = s.index(nonprintable)) >= 0)
	s.at(index,1) = ESC + octstring(toascii(s[index]));

    // escape " with backslash
    index = 0;
    while ( (index = s.index(QUOTE,index)) >= 0) {
	s.at(index,1) = ESCQUOTE;
	index += ESCQUOTE.length();
    }

    return s;
}

// Un-escape special characters, quotes and backslashes from an HDF attribute.
// Note: A regex to match one \ must be defined as
//          Regex foo = "\\\\";
//       because both C++ strings and libg++ regex's also employ \ as
//       an escape character!
String unescattr(String s) {
    static Regex escregx = "\\\\[01][0-7][0-7]";  // matches 4 characters
    static Regex escquoteregex = "[^\\\\]\\\\\"";  // matches 3 characters
    static Regex escescregex = "\\\\\\\\";      // matches 2 characters
    const char ESC = '\\';
    const char QUOTE = '\"';
    const String ESCQUOTE = (String)ESC + (String)QUOTE;

    // unescape any octal-escaped ASCII characters
    int index = 0;
    while ( (index = s.index(escregx,index)) >= 0) {
	s.at(index,4) = unoctstring(s.at(index+1,3));
	index++;
    }

    // unescape any escaped quotes
    index = 0;
    while ( (index = s.index(escquoteregex,index)) >= 0) {
	s.at(index+1,2) = QUOTE;
	index++;
    }

    // unescape any escaped backslashes
    index = 0;
    while ( (index = s.index(escescregex,index)) >= 0) {
	s.at(index,2) = ESC;
	index++;
    }

    return s;
}
<|endoftext|>


<commit_before>/**
 * \file
 * \brief PendSV_Handler() for ARMv7-M (Cortex-M3 / Cortex-M4)
 *
 * \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/internal/scheduler/getScheduler.hpp"
#include "distortos/internal/scheduler/Scheduler.hpp"

#include "distortos/chip/CMSIS-proxy.h"

namespace distortos
{

namespace
{

/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/

/**
 * \brief Wrapper for void* distortos::internal::getScheduler().switchContext(void*)
 *
 * \param [in] stackPointer is the current value of current thread's stack pointer
 *
 * \return new thread's stack pointer
 */

void* schedulerSwitchContextWrapper(void* const stackPointer)
{
	return internal::getScheduler().switchContext(stackPointer);
}

}	// namespace

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

/**
 * \brief PendSV_Handler() for ARMv7-M (Cortex-M3 / Cortex-M4)
 *
 * Performs the context switch.
 */

extern "C" __attribute__ ((naked)) void PendSV_Handler()
{
#if CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0

	constexpr auto basepriValue = CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI << (8 - __NVIC_PRIO_BITS);
	static_assert(basepriValue > 0 && basepriValue <= UINT8_MAX,
			"Invalid CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI value!");

	asm volatile
	(
			"	mov			r0, %[basepriValue]				\n"
			"	msr			basepri, r0						\n"	// enable interrupt masking

			::	[basepriValue] "i" (basepriValue)
	);

#else	// CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0

	asm volatile
	(
			"	cpsid		i								\n"	// disable interrupts
	);

#endif	// CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0

	asm volatile
	(
			"	mrs			r0, PSP							\n"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
			"	tst			lr, #(1 << 4)					\n"	// was floating-point used by the thread?
			"	it			eq								\n"
			"	vstmdbeq	r0!, {s16-s31}					\n"	// save "floating-point" context of current thread
			// save "regular" context of current thread (r12 is saved just to keep double-word alignment)
			"	stmdb		r0!, {r4-r12, lr}				\n"
#else
			"	stmdb		r0!, {r4-r11}					\n"	// save context of current thread
			"	mov			r4, lr							\n"
#endif	// __FPU_PRESENT == 1 && __FPU_USED == 1
			"												\n"
			"	bl			%[schedulerSwitchContext]		\n"	// switch context
			"												\n"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
			"	ldmia		r0!, {r4-r12, lr}				\n"	// load "regular" context of new thread
			"	tst			lr, #(1 << 4)					\n"	// was floating-point used by the thread?
			"	it			eq								\n"
			"	vldmiaeq	r0!, {s16-s31}					\n"	// load "floating-point" context of new thread
#else
			"	mov			lr, r4							\n"
			"	ldmia		r0!, {r4-r11}					\n"	// load context of new thread
#endif	// __FPU_PRESENT == 1 && __FPU_USED == 1
			"	msr			PSP, r0							\n"

			::	[schedulerSwitchContext] "i" (schedulerSwitchContextWrapper)
	);

	asm volatile
	(
#if CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
			"	mov			r0, #0							\n"
			"	msr			basepri, r0						\n"	// disable interrupt masking
#else	// CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
			"	cpsie		i								\n"	// enable interrupts
#endif	// CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
			"												\n"
			"	bx			lr								\n"	// return to new thread
	);

	__builtin_unreachable();
}

}	// namespace distortos
<commit_msg>Modify ARMv7-M-PendSV_Handler.cpp to work for ARMv6-M too<commit_after>/**
 * \file
 * \brief PendSV_Handler() for ARMv7-M (Cortex-M3 / Cortex-M4)
 *
 * \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/internal/scheduler/getScheduler.hpp"
#include "distortos/internal/scheduler/Scheduler.hpp"

#include "distortos/chip/CMSIS-proxy.h"

namespace distortos
{

namespace
{

/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/

/**
 * \brief Wrapper for void* distortos::internal::getScheduler().switchContext(void*)
 *
 * \param [in] stackPointer is the current value of current thread's stack pointer
 *
 * \return new thread's stack pointer
 */

void* schedulerSwitchContextWrapper(void* const stackPointer)
{
	return internal::getScheduler().switchContext(stackPointer);
}

}	// namespace

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

/**
 * \brief PendSV_Handler() for ARMv7-M (Cortex-M3 / Cortex-M4)
 *
 * Performs the context switch.
 */

extern "C" __attribute__ ((naked)) void PendSV_Handler()
{
#if CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0

	constexpr auto basepriValue = CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI << (8 - __NVIC_PRIO_BITS);
	static_assert(basepriValue > 0 && basepriValue <= UINT8_MAX,
			"Invalid CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI value!");

	asm volatile
	(
			"	mov			r0, %[basepriValue]				\n"
			"	msr			basepri, r0						\n"	// enable interrupt masking

			::	[basepriValue] "i" (basepriValue)
	);

#else	// CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0

	asm volatile
	(
			"	cpsid		i								\n"	// disable interrupts
	);

#endif	// CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0

#ifdef __ARM_ARCH_6M__

	asm volatile
	(
			"	mrs			r0, PSP							\n"
			"	sub			r0, #0x10						\n"
			"	stmia		r0!, {r4-r7}					\n"	// save lower half of current thread's context
			"	mov			r4, r8							\n"
			"	mov			r5, r9							\n"
			"	mov			r6, r10							\n"
			"	mov			r7, r11							\n"
			"	sub			r0, #0x20						\n"
			"	stmia		r0!, {r4-r7}					\n"	// save upper half of current thread's context
			"	sub			r0, #0x10						\n"
			"	mov			r4, lr							\n"
			"												\n"
			"	ldr			r1, =%[schedulerSwitchContext]	\n"
			"	blx			r1								\n"	// switch context
			"												\n"
			"	mov			lr, r4							\n"
			"	ldmia		r0!, {r4-r7}					\n"	// load upper half of new thread's context
			"	mov			r8, r4							\n"
			"	mov			r9, r5							\n"
			"	mov			r10, r6							\n"
			"	mov			r11, r7							\n"
			"	ldmia		r0!, {r4-r7}					\n"	// load lower half of new thread's context
			"	msr			PSP, r0							\n"

			::	[schedulerSwitchContext] "i" (schedulerSwitchContextWrapper)
	);

#else	// !def __ARM_ARCH_6M__

	asm volatile
	(
			"	mrs			r0, PSP							\n"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
			"	tst			lr, #(1 << 4)					\n"	// was floating-point used by the thread?
			"	it			eq								\n"
			"	vstmdbeq	r0!, {s16-s31}					\n"	// save "floating-point" context of current thread
			// save "regular" context of current thread (r12 is saved just to keep double-word alignment)
			"	stmdb		r0!, {r4-r12, lr}				\n"
#else
			"	stmdb		r0!, {r4-r11}					\n"	// save context of current thread
			"	mov			r4, lr							\n"
#endif	// __FPU_PRESENT == 1 && __FPU_USED == 1
			"												\n"
			"	bl			%[schedulerSwitchContext]		\n"	// switch context
			"												\n"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
			"	ldmia		r0!, {r4-r12, lr}				\n"	// load "regular" context of new thread
			"	tst			lr, #(1 << 4)					\n"	// was floating-point used by the thread?
			"	it			eq								\n"
			"	vldmiaeq	r0!, {s16-s31}					\n"	// load "floating-point" context of new thread
#else
			"	mov			lr, r4							\n"
			"	ldmia		r0!, {r4-r11}					\n"	// load context of new thread
#endif	// __FPU_PRESENT == 1 && __FPU_USED == 1
			"	msr			PSP, r0							\n"

			::	[schedulerSwitchContext] "i" (schedulerSwitchContextWrapper)
	);

#endif	// !def __ARM_ARCH_6M__

	asm volatile
	(
#if CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
			"	mov			r0, #0							\n"
			"	msr			basepri, r0						\n"	// disable interrupt masking
#else	// CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
			"	cpsie		i								\n"	// enable interrupts
#endif	// CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
			"												\n"
			"	bx			lr								\n"	// return to new thread
	);

	__builtin_unreachable();
}

}	// namespace distortos
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                          License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "autocalib.hpp"
#include "util.hpp"

using namespace std;
using namespace cv;

void focalsFromHomography(const Mat& H, double &f0, double &f1, bool &f0_ok, bool &f1_ok)
{
    CV_Assert(H.type() == CV_64F && H.size() == Size(3, 3));

    const double* h = reinterpret_cast<const double*>(H.data);

    double d1, d2; // Denominators
    double v1, v2; // Focal squares value candidates

    f1_ok = true;
    d1 = h[6] * h[7];
    d2 = (h[7] - h[6]) * (h[7] + h[6]);
    v1 = -(h[0] * h[1] + h[3] * h[4]) / d1;
    v2 = (h[0] * h[0] + h[3] * h[3] - h[1] * h[1] - h[4] * h[4]) / d2;
    if (v1 < v2) swap(v1, v2);
    if (v1 > 0 && v2 > 0) f1 = sqrt(abs(d1) > abs(d2) ? v1 : v2);
    else if (v1 > 0) f1 = sqrt(v1);
    else f1_ok = false;

    f0_ok = true;
    d1 = h[0] * h[3] + h[1] * h[4];
    d2 = h[0] * h[0] + h[1] * h[1] - h[3] * h[3] - h[4] * h[4];
    v1 = -h[2] * h[5] / d1;
    v2 = (h[5] * h[5] - h[2] * h[2]) / d2;
    if (v1 < v2) swap(v1, v2);
    if (v1 > 0 && v2 > 0) f0 = sqrt(abs(d1) > abs(d2) ? v1 : v2);
    else if (v1 > 0) f0 = sqrt(v1);
    else f0_ok = false;
}

void estimateFocal(const vector<ImageFeatures> &features, const vector<MatchesInfo> &pairwise_matches,
                   vector<double> &focals)
{
    const int num_images = static_cast<int>(features.size());
    focals.resize(num_images);

    vector<double> all_focals;

    for (int i = 0; i < num_images; ++i)
    {
        for (int j = 0; j < num_images; ++j)
        {
            const MatchesInfo &m = pairwise_matches[i*num_images + j];
            if (m.H.empty())
                continue;
            double f0, f1;
            bool f0ok, f1ok;
            focalsFromHomography(m.H, f0, f1, f0ok, f1ok);
            if (f0ok && f1ok)
                all_focals.push_back(sqrt(f0 * f1));
        }
    }

    if (static_cast<int>(all_focals.size()) < num_images - 1)
    {
        LOGLN("Can't estimate focal length, will use anaive approach");
        double focals_sum = 0;
        for (int i = 0; i < num_images; ++i)
            focals_sum += features[i].img_size.width + features[i].img_size.height;
        for (int i = 0; i < num_images; ++i)
            focals[i] = focals_sum / num_images;
    }
    else
    {
        nth_element(all_focals.begin(), all_focals.begin() + all_focals.size()/2, all_focals.end());
        for (int i = 0; i < num_images; ++i)
            focals[i] = all_focals[all_focals.size()/2];
    }
}
<commit_msg>fixed typo in opencv_stitching <commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                          License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "autocalib.hpp"
#include "util.hpp"

using namespace std;
using namespace cv;

void focalsFromHomography(const Mat& H, double &f0, double &f1, bool &f0_ok, bool &f1_ok)
{
    CV_Assert(H.type() == CV_64F && H.size() == Size(3, 3));

    const double* h = reinterpret_cast<const double*>(H.data);

    double d1, d2; // Denominators
    double v1, v2; // Focal squares value candidates

    f1_ok = true;
    d1 = h[6] * h[7];
    d2 = (h[7] - h[6]) * (h[7] + h[6]);
    v1 = -(h[0] * h[1] + h[3] * h[4]) / d1;
    v2 = (h[0] * h[0] + h[3] * h[3] - h[1] * h[1] - h[4] * h[4]) / d2;
    if (v1 < v2) swap(v1, v2);
    if (v1 > 0 && v2 > 0) f1 = sqrt(abs(d1) > abs(d2) ? v1 : v2);
    else if (v1 > 0) f1 = sqrt(v1);
    else f1_ok = false;

    f0_ok = true;
    d1 = h[0] * h[3] + h[1] * h[4];
    d2 = h[0] * h[0] + h[1] * h[1] - h[3] * h[3] - h[4] * h[4];
    v1 = -h[2] * h[5] / d1;
    v2 = (h[5] * h[5] - h[2] * h[2]) / d2;
    if (v1 < v2) swap(v1, v2);
    if (v1 > 0 && v2 > 0) f0 = sqrt(abs(d1) > abs(d2) ? v1 : v2);
    else if (v1 > 0) f0 = sqrt(v1);
    else f0_ok = false;
}

void estimateFocal(const vector<ImageFeatures> &features, const vector<MatchesInfo> &pairwise_matches,
                   vector<double> &focals)
{
    const int num_images = static_cast<int>(features.size());
    focals.resize(num_images);

    vector<double> all_focals;

    for (int i = 0; i < num_images; ++i)
    {
        for (int j = 0; j < num_images; ++j)
        {
            const MatchesInfo &m = pairwise_matches[i*num_images + j];
            if (m.H.empty())
                continue;
            double f0, f1;
            bool f0ok, f1ok;
            focalsFromHomography(m.H, f0, f1, f0ok, f1ok);
            if (f0ok && f1ok)
                all_focals.push_back(sqrt(f0 * f1));
        }
    }

    if (static_cast<int>(all_focals.size()) >= num_images - 1)
    {
        nth_element(all_focals.begin(), all_focals.begin() + all_focals.size()/2, all_focals.end());
        for (int i = 0; i < num_images; ++i)
            focals[i] = all_focals[all_focals.size()/2];
    }
    else
    {
        LOGLN("Can't estimate focal length, will use naive approach");
        double focals_sum = 0;
        for (int i = 0; i < num_images; ++i)
            focals_sum += features[i].img_size.width + features[i].img_size.height;
        for (int i = 0; i < num_images; ++i)
            focals[i] = focals_sum / num_images;
    }
}
<|endoftext|>


<commit_before>/*
 Copyright (c) 2014, Ford Motor Company
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.

 Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following
 disclaimer in the documentation and/or other materials provided with the
 distribution.

 Neither the name of the Ford Motor Company nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */

#include "policy/update_status_manager.h"
#include "policy/policy_listener.h"
#include "utils/logger.h"

namespace policy {

CREATE_LOGGERPTR_GLOBAL(logger_, "Policy")

UpdateStatusManager::UpdateStatusManager()
    : listener_(NULL)
    , exchange_in_progress_(false)
    , update_required_(false)
    , update_scheduled_(false)
    , exchange_pending_(false)
    , apps_search_in_progress_(false)
    , app_registered_from_non_consented_device_(false)
    , last_update_status_(policy::StatusUnknown) {
  update_status_thread_delegate_ = new UpdateThreadDelegate(this);
  thread_ = threads::CreateThread("UpdateStatusThread",
                                  update_status_thread_delegate_);
  thread_->start();
}

UpdateStatusManager::~UpdateStatusManager() {
  LOG4CXX_AUTO_TRACE(logger_);
  DCHECK(update_status_thread_delegate_);
  DCHECK(thread_);
  thread_->join();
  delete update_status_thread_delegate_;
  threads::DeleteThread(thread_);
}

void UpdateStatusManager::set_listener(PolicyListener* listener) {
  listener_ = listener;
}

void UpdateStatusManager::OnUpdateSentOut(uint32_t update_timeout) {
  LOG4CXX_AUTO_TRACE(logger_);
  DCHECK(update_status_thread_delegate_);
  const unsigned milliseconds_in_second = 1000;
  update_status_thread_delegate_->updateTimeOut(update_timeout *
                                                milliseconds_in_second);
  set_exchange_in_progress(true);
  set_exchange_pending(true);
  set_update_required(false);
}

void UpdateStatusManager::OnUpdateTimeoutOccurs() {
  LOG4CXX_AUTO_TRACE(logger_);
  set_update_required(true);
  set_exchange_in_progress(false);
  set_exchange_pending(false);
  DCHECK(update_status_thread_delegate_);
  update_status_thread_delegate_->updateTimeOut(0);  // Stop Timer
}

void UpdateStatusManager::OnValidUpdateReceived() {
  LOG4CXX_AUTO_TRACE(logger_);
  update_status_thread_delegate_->updateTimeOut(0);  // Stop Timer
  set_exchange_pending(false);
  set_exchange_in_progress(false);
}

void UpdateStatusManager::OnWrongUpdateReceived() {
  LOG4CXX_AUTO_TRACE(logger_);
  update_status_thread_delegate_->updateTimeOut(0);  // Stop Timer
  set_update_required(true);
  set_exchange_in_progress(false);
  set_exchange_pending(false);
}

void UpdateStatusManager::OnResetDefaultPT(bool is_update_required) {
  LOG4CXX_AUTO_TRACE(logger_);
  exchange_in_progress_ = false;
  update_required_ = is_update_required;
  exchange_pending_ = false;
  last_update_status_ = policy::StatusUnknown;
}

void UpdateStatusManager::OnResetRetrySequence() {
  LOG4CXX_AUTO_TRACE(logger_);
  if (exchange_in_progress_) {
    set_exchange_pending(true);
  }
  set_update_required(true);
}

void UpdateStatusManager::OnNewApplicationAdded(const DeviceConsent consent) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (kDeviceAllowed != consent) {
    app_registered_from_non_consented_device_ = true;
    return;
  }
  app_registered_from_non_consented_device_ = false;
  set_update_required(true);
}

void UpdateStatusManager::OnPolicyInit(bool is_update_required) {
  LOG4CXX_AUTO_TRACE(logger_);
  update_required_ = is_update_required;
}

void UpdateStatusManager::OnDeviceConsented() {
  LOG4CXX_AUTO_TRACE(logger_);
  if (app_registered_from_non_consented_device_) {
    set_update_required(true);
  }
}

PolicyTableStatus UpdateStatusManager::GetUpdateStatus() const {
  LOG4CXX_AUTO_TRACE(logger_);
  if (!exchange_in_progress_ && !exchange_pending_ && !update_required_) {
    return PolicyTableStatus::StatusUpToDate;
  }

  if (update_required_ && !exchange_in_progress_ && !exchange_pending_) {
    return PolicyTableStatus::StatusUpdateRequired;
  }

  return PolicyTableStatus::StatusUpdatePending;
}

bool UpdateStatusManager::IsUpdateRequired() const {
  return update_required_ || update_scheduled_;
}

bool UpdateStatusManager::IsUpdatePending() const {
  return exchange_pending_;
}

void UpdateStatusManager::ScheduleUpdate() {
  update_scheduled_ = true;
  update_required_ = true;
}

void UpdateStatusManager::ResetUpdateSchedule() {
  update_scheduled_ = false;
}

std::string UpdateStatusManager::StringifiedUpdateStatus() const {
  switch (GetUpdateStatus()) {
    case policy::StatusUpdatePending:
      return "UPDATING";
    case policy::StatusUpdateRequired:
      return "UPDATE_NEEDED";
    case policy::StatusUpToDate:
      return "UP_TO_DATE";
    default: { return "UNKNOWN"; }
  }
}

void policy::UpdateStatusManager::OnAppsSearchStarted() {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
  apps_search_in_progress_ = true;
}

void policy::UpdateStatusManager::OnAppsSearchCompleted() {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
  apps_search_in_progress_ = false;
}

bool policy::UpdateStatusManager::IsAppsSearchInProgress() {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
  return apps_search_in_progress_;
}

void UpdateStatusManager::CheckUpdateStatus() {
  LOG4CXX_AUTO_TRACE(logger_);
  policy::PolicyTableStatus status = GetUpdateStatus();
  if (listener_ && last_update_status_ != status) {
    LOG4CXX_INFO(logger_, "Send OnUpdateStatusChanged");
    listener_->OnUpdateStatusChanged(StringifiedUpdateStatus());
  }
  last_update_status_ = status;
}

void UpdateStatusManager::set_exchange_in_progress(bool value) {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock lock(exchange_in_progress_lock_);
  LOG4CXX_INFO(logger_,
               "Exchange in progress value is:" << std::boolalpha << value);
  exchange_in_progress_ = value;
  CheckUpdateStatus();
}

void UpdateStatusManager::set_exchange_pending(bool value) {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock lock(exchange_pending_lock_);
  LOG4CXX_INFO(logger_,
               "Exchange pending value is:" << std::boolalpha << value);
  exchange_pending_ = value;
  CheckUpdateStatus();
}

void UpdateStatusManager::set_update_required(bool value) {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock lock(update_required_lock_);
  LOG4CXX_INFO(logger_, "Update required value is:" << std::boolalpha << value);
  update_required_ = value;
  CheckUpdateStatus();
}

UpdateStatusManager::UpdateThreadDelegate::UpdateThreadDelegate(
    UpdateStatusManager* update_status_manager)
    : timeout_(0)
    , stop_flag_(false)
    , state_lock_(true)
    , update_status_manager_(update_status_manager) {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(logger_, "Create UpdateThreadDelegate");
}

UpdateStatusManager::UpdateThreadDelegate::~UpdateThreadDelegate() {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(logger_, "Delete UpdateThreadDelegate");
}

void UpdateStatusManager::UpdateThreadDelegate::threadMain() {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(logger_, "UpdateStatusManager thread started (started normal)");
  sync_primitives::AutoLock auto_lock(state_lock_);
  while (false == stop_flag_) {
    if (timeout_ > 0) {
      LOG4CXX_DEBUG(logger_, "Timeout is greater then 0");
      sync_primitives::ConditionalVariable::WaitStatus wait_status =
          termination_condition_.WaitFor(auto_lock, timeout_);
      if (sync_primitives::ConditionalVariable::kTimeout == wait_status) {
        if (update_status_manager_) {
          update_status_manager_->OnUpdateTimeoutOccurs();
        }
      }
    } else {
      // Time is not active, wait until timeout will be set,
      // or UpdateStatusManager will be deleted
      termination_condition_.Wait(auto_lock);
    }
  }
}

void UpdateStatusManager::UpdateThreadDelegate::exitThreadMain() {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock auto_lock(state_lock_);
  stop_flag_ = true;
  LOG4CXX_DEBUG(logger_, "before notify");
  termination_condition_.NotifyOne();
}

void UpdateStatusManager::UpdateThreadDelegate::updateTimeOut(
    const uint32_t timeout_ms) {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock auto_lock(state_lock_);
  timeout_ = timeout_ms;
  termination_condition_.NotifyOne();
}

}  // namespace policy
<commit_msg>Makes default value for app registerd from non-consented device<commit_after>/*
 Copyright (c) 2014, Ford Motor Company
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.

 Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following
 disclaimer in the documentation and/or other materials provided with the
 distribution.

 Neither the name of the Ford Motor Company nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */

#include "policy/update_status_manager.h"
#include "policy/policy_listener.h"
#include "utils/logger.h"

namespace policy {

CREATE_LOGGERPTR_GLOBAL(logger_, "Policy")

UpdateStatusManager::UpdateStatusManager()
    : listener_(NULL)
    , exchange_in_progress_(false)
    , update_required_(false)
    , update_scheduled_(false)
    , exchange_pending_(false)
    , apps_search_in_progress_(false)
    , app_registered_from_non_consented_device_(true)
    , last_update_status_(policy::StatusUnknown) {
  update_status_thread_delegate_ = new UpdateThreadDelegate(this);
  thread_ = threads::CreateThread("UpdateStatusThread",
                                  update_status_thread_delegate_);
  thread_->start();
}

UpdateStatusManager::~UpdateStatusManager() {
  LOG4CXX_AUTO_TRACE(logger_);
  DCHECK(update_status_thread_delegate_);
  DCHECK(thread_);
  thread_->join();
  delete update_status_thread_delegate_;
  threads::DeleteThread(thread_);
}

void UpdateStatusManager::set_listener(PolicyListener* listener) {
  listener_ = listener;
}

void UpdateStatusManager::OnUpdateSentOut(uint32_t update_timeout) {
  LOG4CXX_AUTO_TRACE(logger_);
  DCHECK(update_status_thread_delegate_);
  const unsigned milliseconds_in_second = 1000;
  update_status_thread_delegate_->updateTimeOut(update_timeout *
                                                milliseconds_in_second);
  set_exchange_in_progress(true);
  set_exchange_pending(true);
  set_update_required(false);
}

void UpdateStatusManager::OnUpdateTimeoutOccurs() {
  LOG4CXX_AUTO_TRACE(logger_);
  set_update_required(true);
  set_exchange_in_progress(false);
  set_exchange_pending(false);
  DCHECK(update_status_thread_delegate_);
  update_status_thread_delegate_->updateTimeOut(0);  // Stop Timer
}

void UpdateStatusManager::OnValidUpdateReceived() {
  LOG4CXX_AUTO_TRACE(logger_);
  update_status_thread_delegate_->updateTimeOut(0);  // Stop Timer
  set_exchange_pending(false);
  set_exchange_in_progress(false);
}

void UpdateStatusManager::OnWrongUpdateReceived() {
  LOG4CXX_AUTO_TRACE(logger_);
  update_status_thread_delegate_->updateTimeOut(0);  // Stop Timer
  set_update_required(true);
  set_exchange_in_progress(false);
  set_exchange_pending(false);
}

void UpdateStatusManager::OnResetDefaultPT(bool is_update_required) {
  LOG4CXX_AUTO_TRACE(logger_);
  exchange_in_progress_ = false;
  update_required_ = is_update_required;
  exchange_pending_ = false;
  last_update_status_ = policy::StatusUnknown;
}

void UpdateStatusManager::OnResetRetrySequence() {
  LOG4CXX_AUTO_TRACE(logger_);
  if (exchange_in_progress_) {
    set_exchange_pending(true);
  }
  set_update_required(true);
}

void UpdateStatusManager::OnNewApplicationAdded(const DeviceConsent consent) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (kDeviceAllowed != consent) {
    app_registered_from_non_consented_device_ = true;
    return;
  }
  app_registered_from_non_consented_device_ = false;
  set_update_required(true);
}

void UpdateStatusManager::OnPolicyInit(bool is_update_required) {
  LOG4CXX_AUTO_TRACE(logger_);
  update_required_ = is_update_required;
}

void UpdateStatusManager::OnDeviceConsented() {
  LOG4CXX_AUTO_TRACE(logger_);
  if (app_registered_from_non_consented_device_) {
    set_update_required(true);
  }
}

PolicyTableStatus UpdateStatusManager::GetUpdateStatus() const {
  LOG4CXX_AUTO_TRACE(logger_);
  if (!exchange_in_progress_ && !exchange_pending_ && !update_required_) {
    return PolicyTableStatus::StatusUpToDate;
  }

  if (update_required_ && !exchange_in_progress_ && !exchange_pending_) {
    return PolicyTableStatus::StatusUpdateRequired;
  }

  return PolicyTableStatus::StatusUpdatePending;
}

bool UpdateStatusManager::IsUpdateRequired() const {
  return update_required_ || update_scheduled_;
}

bool UpdateStatusManager::IsUpdatePending() const {
  return exchange_pending_;
}

void UpdateStatusManager::ScheduleUpdate() {
  update_scheduled_ = true;
  update_required_ = true;
}

void UpdateStatusManager::ResetUpdateSchedule() {
  update_scheduled_ = false;
}

std::string UpdateStatusManager::StringifiedUpdateStatus() const {
  switch (GetUpdateStatus()) {
    case policy::StatusUpdatePending:
      return "UPDATING";
    case policy::StatusUpdateRequired:
      return "UPDATE_NEEDED";
    case policy::StatusUpToDate:
      return "UP_TO_DATE";
    default: { return "UNKNOWN"; }
  }
}

void policy::UpdateStatusManager::OnAppsSearchStarted() {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
  apps_search_in_progress_ = true;
}

void policy::UpdateStatusManager::OnAppsSearchCompleted() {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
  apps_search_in_progress_ = false;
}

bool policy::UpdateStatusManager::IsAppsSearchInProgress() {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
  return apps_search_in_progress_;
}

void UpdateStatusManager::CheckUpdateStatus() {
  LOG4CXX_AUTO_TRACE(logger_);
  policy::PolicyTableStatus status = GetUpdateStatus();
  if (listener_ && last_update_status_ != status) {
    LOG4CXX_INFO(logger_, "Send OnUpdateStatusChanged");
    listener_->OnUpdateStatusChanged(StringifiedUpdateStatus());
  }
  last_update_status_ = status;
}

void UpdateStatusManager::set_exchange_in_progress(bool value) {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock lock(exchange_in_progress_lock_);
  LOG4CXX_INFO(logger_,
               "Exchange in progress value is:" << std::boolalpha << value);
  exchange_in_progress_ = value;
  CheckUpdateStatus();
}

void UpdateStatusManager::set_exchange_pending(bool value) {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock lock(exchange_pending_lock_);
  LOG4CXX_INFO(logger_,
               "Exchange pending value is:" << std::boolalpha << value);
  exchange_pending_ = value;
  CheckUpdateStatus();
}

void UpdateStatusManager::set_update_required(bool value) {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock lock(update_required_lock_);
  LOG4CXX_INFO(logger_, "Update required value is:" << std::boolalpha << value);
  update_required_ = value;
  CheckUpdateStatus();
}

UpdateStatusManager::UpdateThreadDelegate::UpdateThreadDelegate(
    UpdateStatusManager* update_status_manager)
    : timeout_(0)
    , stop_flag_(false)
    , state_lock_(true)
    , update_status_manager_(update_status_manager) {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(logger_, "Create UpdateThreadDelegate");
}

UpdateStatusManager::UpdateThreadDelegate::~UpdateThreadDelegate() {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(logger_, "Delete UpdateThreadDelegate");
}

void UpdateStatusManager::UpdateThreadDelegate::threadMain() {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(logger_, "UpdateStatusManager thread started (started normal)");
  sync_primitives::AutoLock auto_lock(state_lock_);
  while (false == stop_flag_) {
    if (timeout_ > 0) {
      LOG4CXX_DEBUG(logger_, "Timeout is greater then 0");
      sync_primitives::ConditionalVariable::WaitStatus wait_status =
          termination_condition_.WaitFor(auto_lock, timeout_);
      if (sync_primitives::ConditionalVariable::kTimeout == wait_status) {
        if (update_status_manager_) {
          update_status_manager_->OnUpdateTimeoutOccurs();
        }
      }
    } else {
      // Time is not active, wait until timeout will be set,
      // or UpdateStatusManager will be deleted
      termination_condition_.Wait(auto_lock);
    }
  }
}

void UpdateStatusManager::UpdateThreadDelegate::exitThreadMain() {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock auto_lock(state_lock_);
  stop_flag_ = true;
  LOG4CXX_DEBUG(logger_, "before notify");
  termination_condition_.NotifyOne();
}

void UpdateStatusManager::UpdateThreadDelegate::updateTimeOut(
    const uint32_t timeout_ms) {
  LOG4CXX_AUTO_TRACE(logger_);
  sync_primitives::AutoLock auto_lock(state_lock_);
  timeout_ = timeout_ms;
  termination_condition_.NotifyOne();
}

}  // namespace policy
<|endoftext|>


<commit_before>/*
 * Copyright © 2013 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

/**
 * \file brw_lower_unnormalized_offset.cpp
 *
 * IR lower pass to convert a texture offset into an adjusted coordinate,
 * for use with unnormalized coordinates. At least the gather4* messages
 * on Ivybridge and Haswell make a mess with nonzero offsets.
 *
 * \author Chris Forbes <chrisf@ijw.co.nz>
 */

#include "glsl/glsl_types.h"
#include "glsl/ir.h"
#include "glsl/ir_builder.h"

using namespace ir_builder;

class brw_lower_unnormalized_offset_visitor : public ir_hierarchical_visitor {
public:
   brw_lower_unnormalized_offset_visitor()
   {
      progress = false;
   }

   ir_visitor_status visit_leave(ir_texture *ir);

   bool progress;
};

ir_visitor_status
brw_lower_unnormalized_offset_visitor::visit_leave(ir_texture *ir)
{
   if (!ir->offset)
      return visit_continue;

   if (ir->op == ir_tg4 || ir->op == ir_tex) {
      if (ir->sampler->type->sampler_dimensionality != GLSL_SAMPLER_DIM_RECT)
         return visit_continue;
   }
   else if (ir->op != ir_txf) {
      return visit_continue;
   }

   void *mem_ctx = ralloc_parent(ir);

   if (ir->op == ir_txf) {
      ir_variable *var = new(mem_ctx) ir_variable(ir->coordinate->type,
                                                  "coordinate",
                                                  ir_var_temporary);
      base_ir->insert_before(var);
      base_ir->insert_before(assign(var, ir->coordinate));
      base_ir->insert_before(assign(var,
               add(swizzle_for_size(var, ir->offset->type->vector_elements), ir->offset),
               (1 << ir->offset->type->vector_elements) - 1));

      ir->coordinate = new(mem_ctx) ir_dereference_variable(var);
   } else {
      ir->coordinate = add(ir->coordinate, i2f(ir->offset));
   }

   ir->offset = NULL;

   progress = true;
   return visit_continue;
}

extern "C" {

bool
brw_do_lower_unnormalized_offset(exec_list *instructions)
{
   brw_lower_unnormalized_offset_visitor v;

   visit_list_elements(&v, instructions);

   return v.progress;
}

}
<commit_msg>i965: Restore a lost comment about TXF offset bugs.<commit_after>/*
 * Copyright © 2013 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

/**
 * \file brw_lower_unnormalized_offset.cpp
 *
 * IR lower pass to convert a texture offset into an adjusted coordinate,
 * for use with unnormalized coordinates. At least the gather4* messages
 * on Ivybridge and Haswell make a mess with nonzero offsets.
 *
 * \author Chris Forbes <chrisf@ijw.co.nz>
 */

#include "glsl/glsl_types.h"
#include "glsl/ir.h"
#include "glsl/ir_builder.h"

using namespace ir_builder;

class brw_lower_unnormalized_offset_visitor : public ir_hierarchical_visitor {
public:
   brw_lower_unnormalized_offset_visitor()
   {
      progress = false;
   }

   ir_visitor_status visit_leave(ir_texture *ir);

   bool progress;
};

ir_visitor_status
brw_lower_unnormalized_offset_visitor::visit_leave(ir_texture *ir)
{
   if (!ir->offset)
      return visit_continue;

   if (ir->op == ir_tg4 || ir->op == ir_tex) {
      if (ir->sampler->type->sampler_dimensionality != GLSL_SAMPLER_DIM_RECT)
         return visit_continue;
   }
   else if (ir->op != ir_txf) {
      return visit_continue;
   }

   void *mem_ctx = ralloc_parent(ir);

   if (ir->op == ir_txf) {
      /* It appears that the ld instruction used for txf does its
       * address bounds check before adding in the offset.  To work
       * around this, just add the integer offset to the integer texel
       * coordinate, and don't put the offset in the header.
       */
      ir_variable *var = new(mem_ctx) ir_variable(ir->coordinate->type,
                                                  "coordinate",
                                                  ir_var_temporary);
      base_ir->insert_before(var);
      base_ir->insert_before(assign(var, ir->coordinate));
      base_ir->insert_before(assign(var,
               add(swizzle_for_size(var, ir->offset->type->vector_elements), ir->offset),
               (1 << ir->offset->type->vector_elements) - 1));

      ir->coordinate = new(mem_ctx) ir_dereference_variable(var);
   } else {
      ir->coordinate = add(ir->coordinate, i2f(ir->offset));
   }

   ir->offset = NULL;

   progress = true;
   return visit_continue;
}

extern "C" {

bool
brw_do_lower_unnormalized_offset(exec_list *instructions)
{
   brw_lower_unnormalized_offset_visitor v;

   visit_list_elements(&v, instructions);

   return v.progress;
}

}
<|endoftext|>