Esempio n. 1
0
static void uninit(struct vf_instance *vf){
	if(!vf->priv) return;

	freeBuffers(&vf->priv->luma);
	freeBuffers(&vf->priv->chroma);

	free(vf->priv);
	vf->priv=NULL;
}
status_t CaptureStream::stop()
{
    LOG2("@%s, name:%s", __FUNCTION__, getName());
    status_t status = NO_ERROR;

    flushMessage();

    // usually the devices are stopped already (see notifyPolledEvent) but just in case..
    if (mCaptureDevice->isStarted()) {
        status = mCaptureDevice->stop(false);
        if (status != OK)
            LOGW("@%s Failed to stream off the capture device", __FUNCTION__);
        else
            LOG1("@%s stopped capture device", __FUNCTION__);
    }
    if (mPostviewDevice->isStarted()) {
        status = mPostviewDevice->stop(false);
        if (status != OK)
            LOGW("@%s Failed to stream off the postview device", __FUNCTION__);
        else
            LOG1("@%s stopped postview device", __FUNCTION__);
    }

    // pools need to be destroyed, or to be exact, the VIDIOC_REQBUFS needs to be sent with 0. See V4L2 spec.
    mCaptureDevice->destroyBufferPool();
    mPostviewDevice->destroyBufferPool();
    mPostviewDevice->close(); // <- crucial. Reason unknown, but please verify still snapshot functionality if you attempt to remove this

    freeBuffers();

    mLastReqId = INVALID_REQ_ID;
    mRawLockEnabled = false;
    mCaptureWithoutPreview = false;
    return status;
}
int PreviewStream::configure(int fps, bool /*videoSnapshot*/)
{
    FLOG_TRACE("PreviewStream %s running", __FUNCTION__);
    int ret = NO_ERROR;
    int errCode = 0;

    fAssert(mDeviceAdapter.get() != NULL);
    ret = mDeviceAdapter->setDeviceConfig(mWidth, mHeight, mFormat, fps);
    if (ret != NO_ERROR) {
        FLOGE("%s setDeviceConfig failed", __FUNCTION__);
        errCode = CAMERA2_MSG_ERROR_DEVICE;
        goto fail;
    }

    mDeviceAdapter->setCameraBufferProvide(this);
    ret = allocateBuffers(mWidth, mHeight, mFormat, mMaxProducerBuffers);
    if (ret != NO_ERROR) {
        FLOGE("%s allocateBuffers failed", __FUNCTION__);
        errCode = CAMERA2_MSG_ERROR_REQUEST;
        goto fail;
    }

    mPrepared = true;
    return NO_ERROR;

fail:
    freeBuffers();
    FLOGE("Error occurred, performing cleanup");

    if (NULL != mErrorListener) {
        mErrorListener->handleError(errCode);
    }

    return BAD_VALUE;
}
Esempio n. 4
0
MBOOL
StereoNodeImpl::
onStop()
{
    FUNC_START;
    MBOOL ret = syncWithThread(); //wait for jobs done

    Mutex::Autolock lock(mLock);
    {
        list<PostBufInfo>::iterator iter;
        for(iter = mlPostBufData.begin(); iter != mlPostBufData.end(); iter++)
        {
            MY_LOGD("ReturnBuffer:data(%d), buf(0x%x)",
                    (*iter).data,
                    (*iter).buf);
            handleReturnBuffer(
                (*iter).data,
                (MUINTPTR)((*iter).buf),
                0);
        }
    }
    while(muEnqFrameCnt > muDeqFrameCnt)
    {
        MY_LOGD("wait lock enq %d > deq %d", muEnqFrameCnt, muDeqFrameCnt);
        mCondDeque.wait(mLock);
        MY_LOGD("wait done");
    }
    //
    freeBuffers();
    //
    FUNC_END;
    return ret;
}
status_t FakeStreamManager::FakeStream::stop()
{
    LOG2("@%s", __FUNCTION__);

    freeBuffers();
    return NO_ERROR;
}
status_t FakeStreamManager::FakeStream::allocateBuffers()
{
    LOG2("@%s", __FUNCTION__);

    Mutex::Autolock _l(mBuffersLock);
    if (mBuffers.size() || mBuffersInDevice.size()) {
        LOGW("%s: buffers are allocated!", __FUNCTION__);
        return NO_ERROR;
    }

    for (int i = 0; i < mBufsNum; i++) {
        sp<CameraBuffer> buf = MemoryUtils::allocateHeapBuffer(
                                      mConfig.width,
                                      mConfig.height,
                                      widthToStride(GFXFmt2V4l2Fmt(mConfig.format, mCameraId), mConfig.width),
                                      GFXFmt2V4l2Fmt(mConfig.format, mCameraId), mCameraId);
        if (buf.get()) {
            mBuffers.push_back(buf);
        } else {
            LOGE("%s: no memory for fake stream %d!", __FUNCTION__, mType);
            freeBuffers();
            return UNKNOWN_ERROR;
        }
    }
    return NO_ERROR;
}
Esempio n. 7
0
// the principal program sequence
void VisionEngine::start() {
    
	if (!interface_) interface_ = new ConsoleInterface(app_name_.c_str());
	
	if (!interface_->openDisplay(this)) {
		delete interface_;
		interface_ = new ConsoleInterface(app_name_.c_str());
		interface_->openDisplay(this);
	}
	
    if(camera_==NULL ) {
        interface_->displayError("No camera found!");
        return;
    }
    
    if( camera_->startCamera() ) {
        
        initFrameProcessors();
        startThread();
        mainLoop();
        stopThread();
        
    } else interface_->displayError("Could not start camera!");
    
    teardownCamera();
    freeBuffers();
}
status_t CaptureStream::allocateBuffers(int bufsNum)
{
    if (mPostviewBuffers.size()) {
        LOGW("%s: Already have buffers!", __FUNCTION__);
        return NO_ERROR;
    }

    // Fill up the empty v4L2 buffers
    for (int i = 0 ; i < bufsNum; i++) {
        struct v4l2_buffer v4l2Buf;
        CLEAR(v4l2Buf);
        mV4l2PostviewBuffers.push(v4l2Buf);
        mV4l2CaptureBuffers.push(v4l2Buf);
    }

    // Allocate internal buffers for postview
    for (int i = 0; i < bufsNum; i++) {
        sp<CameraBuffer> buf = MemoryUtils::allocateHeapBuffer(
                                      mPostviewConfig.width,
                                      mPostviewConfig.height,
                                      mPostviewConfig.stride,
                                      PlatformData::getV4L2PixelFmtForGfxHalFmt(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, mCameraId),
                                      mCameraId);
        if (buf.get()) {
            mPostviewBuffers.push_back(buf);
            mV4l2PostviewBuffers.editItemAt(i).m.userptr = (unsigned long int)buf->data();
        } else {
            LOGE("%s: no memory for postview!", __FUNCTION__);
            freeBuffers();
            return UNKNOWN_ERROR;
        }
    }
    return NO_ERROR;
}
status_t MetadataQueue::setStreamSlot(const List<camera_metadata_t*> &bufs) {
    if (mStreamSlotCount > 0) {
        freeBuffers(mStreamSlot.begin(), mStreamSlot.end());
    }
    mStreamSlot = bufs;
    mStreamSlotCount = mStreamSlot.size();

    return OK;
}
void AnatomyOMXClient::stop() {
	changeState(OMX_StateIdle);
	sleep(1);
	changeState(OMX_StateLoaded);
	freeBuffers();
	sleep(1);

	deinit();
}
Esempio n. 11
0
//==============================================================================
void BufferedOutputStream::close()
{
	if(m_rpOutputStream)
	{
		flushBuffers();
		freeBuffers();
		m_rpOutputStream->close();
		m_rpOutputStream.release();
	}
}
Esempio n. 12
0
void GuitarSori::init( const int mFramesPerBuffer, const int mNumChannels, const int mSampleSize, PaSampleFormat mSampleFormat, const double mSampleRate)
{
	int numBytes, numBytesConverted;

	framesPerBuffer = mFramesPerBuffer;
	numChannels = mNumChannels;
	sampleSize = mSampleSize;
	sampleFormat = mSampleFormat;
	sampleRate = mSampleRate;

	numBytes = mFramesPerBuffer * mNumChannels * mSampleSize;
	numBytesConverted = mFramesPerBuffer * mNumChannels * 8;

	freeBuffers();
	sampleBlock = (char *)malloc(numBytes);
	sampleBlockConverted = (double *)malloc(numBytesConverted);
	sampleBlockFFT = (double *)malloc(numBytesConverted / 2);

	if ( !isBuffersReady() )
	{
		printf("Cannot allocate sample block\n");
		return;
	}

	memset(sampleBlock, 0x00, numBytes);
	memset(sampleBlockConverted, 0x00, numBytesConverted);
	memset(sampleBlockFFT, 0x00, numBytesConverted / 2);

	err = Pa_Initialize();

	printf("──────────────────────────────\n");
	inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */
	inputParameters.device = 1;
	printf("Input device # %d. : %s\n", inputParameters.device, Pa_GetDeviceInfo(inputParameters.device)->name);
	printf("Input LL: %g s\n", Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency);
	printf("Input HL: %g s\n", Pa_GetDeviceInfo(inputParameters.device)->defaultHighInputLatency);
	printf("Input HL: %g s\n", Pa_GetDeviceInfo(inputParameters.device)->defaultHighInputLatency);
	printf("Input Channel(MAX.) : %d ", Pa_GetDeviceInfo(inputParameters.device)->maxInputChannels);
	inputParameters.channelCount = numChannels;
	inputParameters.sampleFormat = sampleFormat;
	inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultHighInputLatency;
	inputParameters.hostApiSpecificStreamInfo = NULL;

	outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
	printf("Output device # %d.\n", outputParameters.device);
	printf("Output LL: %g s\n", Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency);
	printf("Output HL: %g s\n", Pa_GetDeviceInfo(outputParameters.device)->defaultHighOutputLatency);
	outputParameters.channelCount = numChannels;
	outputParameters.sampleFormat = sampleFormat;
	outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultHighOutputLatency;
	outputParameters.hostApiSpecificStreamInfo = NULL;

	err = Pa_OpenStream(&stream, &inputParameters, &outputParameters, sampleRate, framesPerBuffer, paClipOff, NULL, NULL);
	err = Pa_StartStream(stream);
}
status_t MetadataQueue::setStreamSlot(camera_metadata_t *buf) {
    if (buf == NULL) {
        freeBuffers(mStreamSlot.begin(), mStreamSlot.end());
        mStreamSlotCount = 0;
        return OK;
    }
    if (mStreamSlotCount > 1) {
        List<camera_metadata_t*>::iterator deleter = ++mStreamSlot.begin();
        freeBuffers(++mStreamSlot.begin(), mStreamSlot.end());
        mStreamSlotCount = 1;
    }
    if (mStreamSlotCount == 1) {
        free_camera_metadata( *(mStreamSlot.begin()) );
        *(mStreamSlot.begin()) = buf;
    } else {
        mStreamSlot.push_front(buf);
        mStreamSlotCount = 1;
    }
    return OK;
}
OMX_ERRORTYPE EnableDataFlow::resetComponents()
{
    DBGT_PROLOG("");

    OMX_ERRORTYPE err = OMX_ErrorNone;

    DBGT_PTRACE("Sending Command StateIdle to SwJpegEnc");
    err = OMX_SendCommand(mSwJpegEnc, OMX_CommandStateSet, OMX_StateIdle, NULL);
    if(OMX_ErrorNone != err) {
        DBGT_CRITICAL("Sending OMX_StateIdle failed for SwJpegEnc err = %d", err);
        DBGT_EPILOG("");
        return err;
    }

    DBGT_PTRACE("Sending Command StateIdle to ArmIv");
    err = OMX_SendCommand(mArmIvProc, OMX_CommandStateSet, OMX_StateIdle, NULL);
    if(OMX_ErrorNone != err) {
        DBGT_CRITICAL("Sending OMX_StateIdle failed for ArmIVProc err = %d", err);
        DBGT_EPILOG("");
        return err;
    }

    mStateArmIvSem.wait();
    mStateSWJpegSem.wait();

    DBGT_PTRACE("Sending Command StateLoaded to ArmIv");
    err = OMX_SendCommand(mArmIvProc, OMX_CommandStateSet, OMX_StateLoaded, NULL);
    if(OMX_ErrorNone != err) {
        DBGT_CRITICAL("Sending OMX_StateLoaded failed for ArmIVProc err = %d", err);
        DBGT_EPILOG("");
        return err;
    }

    DBGT_PTRACE("Sending Command StateLoaded to SwJpegEnc");
    err = OMX_SendCommand(mSwJpegEnc, OMX_CommandStateSet, OMX_StateLoaded, NULL);
    if(OMX_ErrorNone != err) {
        DBGT_CRITICAL("Sending OMX_StateLoaded failed for SwJpegEnc err = %d", err);
        DBGT_EPILOG("");
        return err;
    }

    err = freeBuffers();
    if(OMX_ErrorNone != err) {
        DBGT_CRITICAL("Free buffers err = %d", err);
        DBGT_EPILOG("");
        return err;
    }

    mStateSWJpegSem.wait();
    mStateArmIvSem.wait();

    DBGT_EPILOG("");
    return err;
}
Esempio n. 15
0
//==============================================================================
BufferedOutputStream::~BufferedOutputStream()
{
	if(m_rpOutputStream)
	{
		try
		{
			writeBuffer();
		}
		catch(IOException& /*e*/)
		{
		}
	}
	freeBuffers();
}
// the principal program sequence
void PortVideoSDL::run() {

	if( !setupCamera() ) {
		if( !setupWindow() ) return;
		showError("No camera found!");
		teardownWindow();
		return;
	}

	if( !setupWindow() ) return;

	allocateBuffers();
	initFrameProcessors();

	bool success = camera_->startCamera();

	if( success ){
		SDL_FillRect(window_,0,0);
		SDL_Flip(window_);
	
		// add the help message from all FrameProcessors
		for (frame = processorList.begin(); frame!=processorList.end(); frame++) {
                        std::vector<std::string> processor_text = (*frame)->getOptions();
			if (processor_text.size()>0) help_text.push_back("");
			for(std::vector<std::string>::iterator processor_line = processor_text.begin(); processor_line!=processor_text.end(); processor_line++) {
				help_text.push_back(*processor_line);
			} 
		}
		
		//print the help message
		for(std::vector<std::string>::iterator help_line = help_text.begin(); help_line!=help_text.end(); help_line++) {
			std::cout << *help_line << std::endl;
		} std::cout << std::endl;

		running_=true;
		cameraThread = SDL_CreateThread(getFrameFromCamera,this);
		controlThread= SDL_CreateThread(getControlMessage,this);
		mainLoop();
		
		SDL_KillThread(cameraThread);
		SDL_KillThread(controlThread);
		teardownCamera();
	} else {
		showError("Could not start camera!");
	}	

	teardownWindow();
	freeBuffers();
	
}
Esempio n. 17
0
void VisionEngine::resetCamera(CameraConfig *cam_cfg) {

	//teardownCamera();
	freeBuffers();
	if (cam_cfg!=NULL) CameraTool::setCameraConfig(cam_cfg);
	setupCamera();
	
	if( camera_->startCamera() ) {
		interface_->closeDisplay();
		interface_->setBuffers(sourceBuffer_,destBuffer_,width_,height_,format_);
		interface_->openDisplay(this);
		for (frame = processorList.begin(); frame!=processorList.end();frame++)
			(*frame)->init(width_ , height_, format_, format_);
	} else interface_->displayError("Could not start camera!");
	
	pause_ = false;
}
Esempio n. 18
0
static void
doPage(FILE *             const ifP, 
       struct cmdlineInfo const cmdline) {

    bit * bitrow;
    int rows, cols, format, row;
    unsigned int blankRows;
    bool rowIsBlank;

    pbm_readpbminit(ifP, &cols, &rows, &format);

    bitrow = pbm_allocrow(cols);

    allocateBuffers(cols);

    putinit(cmdline);

    blankRows = 0;
    prevRowBufferIndex = 0;
    memset(prevRowBuffer, 0, rowBufferSize);

    for (row = 0; row < rows; ++row) {
        pbm_readpbmrow(ifP, bitrow, cols, format);

        convertRow(bitrow, cols, cmdline.pack, cmdline.delta,
                   &rowIsBlank);

        if (rowIsBlank)
            ++blankRows;
        else {
            printBlankRows(blankRows);
            blankRows = 0;
            
            printRow();
        }
    }    
    printBlankRows(blankRows);
    blankRows = 0;

    putrest(!cmdline.noreset);

    freeBuffers();
    pbm_freerow(bitrow);
}
Esempio n. 19
0
void ofxAudioUnitFftNode::setFftBufferSize(unsigned int bufferSize)
{
	_log2N = (unsigned int) ceilf(log2f(bufferSize));
	_N = 1 << _log2N;
	
	// if the new buffer size is bigger than what we've allocated for,
	// free everything and allocate anew (otherwise re-use)
	if(_log2N > _currentMaxLog2N) {
		freeBuffers();
		_fftData.realp = (float *)calloc(_N / 2, sizeof(float));
		_fftData.imagp = (float *)calloc(_N / 2, sizeof(float));
		_window = (float *)calloc(_N, sizeof(float));
		_fftSetup = vDSP_create_fftsetup(_log2N, kFFTRadix2);
		_currentMaxLog2N = _log2N;
	}

	generateWindow(_outputSettings.window, _window, _N);
	setBufferSize(_N);
}
void	SimpleAudioDriver::stop(IOService* inProvider)
{
	//	tear things down
	freeBuffers();
	destroyTimer();
	if(mCommandGate != NULL)
	{
		if(mWorkLoop != NULL)
		{
			mWorkLoop->removeEventSource(mCommandGate);
			mCommandGate->release();
			mCommandGate = NULL;
		}
	}
	if(mWorkLoop != NULL)
	{
		mWorkLoop->release();
		mWorkLoop = NULL;
	}
    IOService::stop(inProvider);
}
Esempio n. 21
0
/* The main function for running the ECG program. */
int runECG() {
	openFile();

	//printf("Peak nr.   Line        R peak\n");
	buffered_filtered_data = makeBuffer(SIZE_FILTERED_DATA);
	buffered_raw_data = makeBuffer(SIZE_RAW_DATA);
	buffered_LP_data = makeBuffer(SIZE_LP_DATA);
	buffered_HP_data = makeBuffer(SIZE_HP_DATA);
	buffered_derivative_square_data = makeBuffer(SIZE_DERIVATIVESQUARE_DATA);
	buffered_peak_lines = makeBuffer(SIZE_PEAKS);
	initQRS();
	while (getFilePointer() != EOF) {
		insert(&buffered_filtered_data, filter());
		detectPeaks();
		line++;
	}

	freeBuffers(&buffered_raw_data, &buffered_LP_data, &buffered_HP_data,
			&buffered_derivative_square_data, &buffered_filtered_data,
			&buffered_peak_lines);
	return 0;
}
Esempio n. 22
0
void module_video_camera::worker()
{
  CvCapture* capture = cvCreateCameraCapture(0);//cvCaptureFromCAM(0);
  if(!capture || currentTask() != INITIALIZE_CAPTURE){
    message = "module||ERROR! Cannot initialize camera!!";
    addTask(CLEANUP_CAPTURE);
    return;
  }
  else message = "";

  IplImage *frame;
  Tasks task = INITIALIZE_CAPTURE;
 
  while( task != TERMINATE_CAPTURE ){

    // Fetch a frame if its asked for / couldnt fetch a previous frame / is the first time.
    if( task == FETCH_FRAME || task == IGNORE_FRAME || task == INITIALIZE_CAPTURE ){
      frame = cvQueryFrame(capture);
      if(frame){
        if( !m_bufferReady )
          initializeBuffers(frame->width,frame->height, frame->depth, frame->nChannels);

        cvConvertImage(frame,m_buffer[nextPage()], CV_CVTIMG_SWAP_RB);
        addTask(CONSUME_FRAME);
      }
      else addTask(IGNORE_FRAME);
    }

    usleep(10);
    task = currentTask();
  }

  //Cleanup
  cvReleaseCapture(&capture);
  freeBuffers();
  addTask(CLEANUP_CAPTURE);
}
Esempio n. 23
0
GuitarSori::~GuitarSori()
{
	stopThread();
	freeBuffers();
}
Esempio n. 24
0
int main(int argc, char *argv[])
{

#ifdef ON_DEMAND
    int junk = 0;
#endif

#ifdef MODULE
    int new_sock;
#endif
    /* return status of MPI functions */
    MPI_Status status;
    /* number of pixels of the image */
    int dim = 0;
    /* dimensions of the image */
    int width, height;
    /* image count */
    int num_image = 0, num_worker;
    /* time variables */
    struct timeval tv1, tv2;

    /* fits of Gaussian */
    double fit[DIM_FIT];
    /* image representing Gaussian fit */
    unsigned char *image = NULL;

    /* indexes */
    int i = 0;

    /* Gauss matrix and vector have contiguous space in memory */
    double *data =
	(double *) malloc(sizeof(double) * DIM_FIT * (DIM_FIT + 1));
    gsl_matrix_view matrice =
	gsl_matrix_view_array(data, DIM_FIT, DIM_FIT);
    gsl_vector_view vettore =
	gsl_vector_view_array(data + (DIM_FIT * DIM_FIT), DIM_FIT);


	/*********************************************************************
	 INIT
	 *********************************************************************/

    srand(time(NULL));
    /* in order to recover from an error */
    gsl_set_error_handler_off();

    /* Initialize of MPI */
    MPI_Init(&argc, &argv);

    /* check the input parameters */
    if (argc != 3) {
	fprintf(stderr, "Invalid number of parameters\n");
	MPI_Abort(MPI_COMM_WORLD, MPI_ERR_ARG);
    }

    /* Every process takes the own rank */
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

    /* Total number of processes */
    MPI_Comm_size(MPI_COMM_WORLD, &p);

    /* check for the number of processes */
    if (p <= PS) {
	fprintf(stderr, "Number of process not valid\n");
	MPI_Abort(MPI_COMM_WORLD, MPI_ERR_OP);
    }

    /* number of workers */
    num_worker = p - PS;

    /* first image is used to estimate gaussian parameters */
    if (my_rank == EMITTER) {

#ifdef DEBUG
	printf("Emitter with rank %d\n", my_rank);
#endif

#ifdef MODULE
	new_sock = Connect();

	if (Read(new_sock, &width, sizeof(int)) < 0)
	    error("Error reading the integers");
	if (Read(new_sock, &height, sizeof(int)) < 0)
	    error("Error reading the integers");

	dim = width * height;
	image = (unsigned char *) malloc(dim);
	/* read from the socket */
	if (Read(new_sock, image, dim) < 0)
	    error("Error reading from socket");
#else
	/* an image representing the gaussian is created and returned
	   as a unsigned char matrix */
	width = atoi(argv[1]);
	height = atoi(argv[2]);
	image = createImage(width, height);
#endif
	/* parameters of the gaussian are estimated */
	initialization(image, width, height, fit);
    }

    /* broadcast data of the image */
    MPI_Bcast(&width, 1, MPI_INT, EMITTER, MPI_COMM_WORLD);
    MPI_Bcast(&height, 1, MPI_INT, EMITTER, MPI_COMM_WORLD);
    MPI_Bcast(&fit, DIM_FIT, MPI_DOUBLE, EMITTER, MPI_COMM_WORLD);

    /* dimension of the image */
    dim = width * height;

	/*********************************************************************
	 EMITTER
	 *********************************************************************/

    if (my_rank == EMITTER) {

	for (i = 0; i < STREAMLENGTH; i++) {

#ifdef DEBUG
	    printf("Emitter sends image %d\n", i);
#endif

	    /* send to the workers the first images */
	    if (i < num_worker) {
		/*      first image is sent to worker */
		MPI_Send(image, dim, MPI_UNSIGNED_CHAR, i + PS, IMAGE,
			 MPI_COMM_WORLD);
	    } else {

#ifdef ON_DEMAND		/* ON_DEMAND */

		/* receive the request */
		MPI_Recv(&junk, 1, MPI_INT, MPI_ANY_SOURCE, REQUEST,
			 MPI_COMM_WORLD, &status);

		/* send the image */
		MPI_Send(image, dim, MPI_UNSIGNED_CHAR, status.MPI_SOURCE,
			 IMAGE, MPI_COMM_WORLD);

#else				/* NOT ON_DEMAND */
		MPI_Send(image, dim, MPI_UNSIGNED_CHAR,
			 i % num_worker + PS, IMAGE, MPI_COMM_WORLD);
#endif
	    }
#ifdef MODULE
	    if (i < STREAMLENGTH - 1) {
		/* read from the socket */
		if (Read(new_sock, image, dim) < 0)
		    error("Error reading from socket");
	    }
#endif

	}

	/* send the termination message */
	for (i = PS; i < p; i++)
	    MPI_Send(NULL, 0, MPI_INT, i, TERMINATION, MPI_COMM_WORLD);


		/*********************************************************************
		 COLLECTOR
		 *********************************************************************/

    } else if (my_rank == COLLECTOR) {
#ifdef DEBUG
	printf("Collector with rank %d\n", my_rank);
#endif

	/* take the time */
	gettimeofday(&tv1, NULL);
	i = 0;
	while (i < num_worker) {

	    MPI_Recv(fit, DIM_FIT, MPI_DOUBLE, MPI_ANY_SOURCE, MPI_ANY_TAG,
		     MPI_COMM_WORLD, &status);

	    if (status.MPI_TAG == TERMINATION) {
#ifdef DEBUG
		printf("Worker %d has ended\n", status.MPI_SOURCE);
#endif
		i++;
	    } else {
		num_image++;
#ifdef DEBUG
		/* PRINTOUT OF THE CURRENT RESULT */
		printf
		    ("Image %d from worker %d: %f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\n",
		     num_image, status.MPI_SOURCE, fit[PAR_A], fit[PAR_X],
		     fit[PAR_Y], fit[PAR_SX], fit[PAR_SY], fit[PAR_a],
		     fit[PAR_b], fit[PAR_c]);
#endif
	    }

	}

	/* take the time */
	gettimeofday(&tv2, NULL);

	/* print parallelism degree, data size and the completion time */
	printf("%d\t%d\t%ld\n", p, dim,
	       (tv2.tv_sec - tv1.tv_sec) * 1000000 + tv2.tv_usec -
	       tv1.tv_usec);

		/*********************************************************************
		 WORKER
		 *********************************************************************/

    } else {
#ifdef DEBUG
	printf("Worker with rank %d\n", my_rank);
#endif

	/* calculate number of pixels and initialize buffers for the fit */
	dim = width * height;
	initBuffers(dim);
	image = (unsigned char *) malloc(dim);

	while (TRUE) {
#ifdef ON_DEMAND
	    /* send the request */
	    MPI_Send(&dim, 1, MPI_INT, EMITTER, REQUEST, MPI_COMM_WORLD);
#endif
	    /* blocking test of incoming message */
	    MPI_Probe(EMITTER, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
	    /* workers ends if receives termination message */
	    if (status.MPI_TAG == TERMINATION) {
#ifdef DEBUG
		printf("Worker %d ends after %d images\n", my_rank,
		       num_image);
#endif
		/* last result is sent to the collector with a different TAG */
		MPI_Send(fit, DIM_FIT, MPI_DOUBLE, COLLECTOR, TERMINATION,
			 MPI_COMM_WORLD);
		freeBuffers();
		break;
	    }

	    /* receive the image from the emitter */
	    MPI_Recv(image, dim, MPI_UNSIGNED_CHAR, EMITTER, IMAGE,
		     MPI_COMM_WORLD, &status);
	    /* calculation of the Gauss matrix and vector */
	    procedure(image, width, height, fit, matrice, vettore, 0);
	    /* solve the system and adjust the fit vector */
	    postProcedure(matrice, vettore, fit);
	    /* send the result to the collector */
	    MPI_Send(fit, DIM_FIT, MPI_DOUBLE, COLLECTOR, RESULTS,
		     MPI_COMM_WORLD);
	}
    }

    /* Finalize of MPI */
    MPI_Finalize();

    return 0;
}
Esempio n. 25
0
/* return 1 on success and 0 on failure.
 * By side effect returns private key, cert, and optionally ca.
 * Parses and decodes the parts of PKCS12
 *
 * NOTE: can parse with USER RSA enabled but may return cert that is not the
 *       pair for the key when using RSA key pairs.
 *
 * pkcs12 : non-null WC_PKCS12 struct
 * psw    : password to use for PKCS12 decode
 * pkey   : Private key returned
 * cert   : x509 cert returned
 * ca     : optional ca returned
 */
int wc_PKCS12_parse(WC_PKCS12* pkcs12, const char* psw,
        byte** pkey, word32* pkeySz, byte** cert, word32* certSz,
        WC_DerCertList** ca)
{
    ContentInfo* ci       = NULL;
    WC_DerCertList* certList = NULL;
    byte* buf             = NULL;
    word32 i, oid;
    int ret, pswSz;

    WOLFSSL_ENTER("wc_PKCS12_parse");

    if (pkcs12 == NULL || psw == NULL || cert == NULL || certSz == NULL ||
        pkey == NULL || pkeySz == NULL) {
        return BAD_FUNC_ARG;
    }
    pswSz = (int)XSTRLEN(psw);
    *cert = NULL;
    *pkey = NULL;
    if (ca != NULL) {
        *ca = NULL;
    }

    /* if there is sign data then verify the MAC */
    if (pkcs12->signData != NULL ) {
        if ((ret = wc_PKCS12_verify(pkcs12, pkcs12->safe->data,
                               pkcs12->safe->dataSz, (byte*)psw, pswSz)) != 0) {
            WOLFSSL_MSG("PKCS12 Bad MAC on verify");
            WOLFSSL_LEAVE("wc_PKCS12_parse verify ", ret);
            return MAC_CMP_FAILED_E;
        }
    }


    /* Decode content infos */
    ci = pkcs12->safe->CI;
    for (i = 0; i < pkcs12->safe->numCI; i++) {
        byte*  data;
        word32 idx = 0;
        int    size, totalSz;

        if (ci->type == WC_PKCS12_ENCRYPTED_DATA) {
            int number;

            WOLFSSL_MSG("Decrypting PKCS12 Content Info Container");
            data = ci->data;
            if (data[idx++] != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC)) {
                freeBuffers(*pkey, buf, pkcs12->heap);
                freeCertList(certList, pkcs12->heap);
                return ASN_PARSE_E;
            }
            if ((ret = GetLength(data, &idx, &size, ci->dataSz)) < 0) {
                freeBuffers(*pkey, buf, pkcs12->heap);
                freeCertList(certList, pkcs12->heap);
                return ret;
            }

            if ((ret = GetSequence(data, &idx, &size, ci->dataSz)) < 0) {
                freeBuffers(*pkey, buf, pkcs12->heap);
                freeCertList(certList, pkcs12->heap);
                return ret;
            }

            if ((ret = GetShortInt(data, &idx, &number, ci->dataSz)) < 0) {
                freeBuffers(*pkey, buf, pkcs12->heap);
                freeCertList(certList, pkcs12->heap);
                return ret;
            }

            if (number != 0) {
                WOLFSSL_MSG("Expecting 0 for Integer with Encrypted PKCS12");
            }

            if ((ret = GetSequence(data, &idx, &size, ci->dataSz)) < 0) {
                freeBuffers(*pkey, buf, pkcs12->heap);
                freeCertList(certList, pkcs12->heap);
                return ret;
            }

            ret = GetObjectId(data, &idx, &oid, oidIgnoreType, ci->dataSz);
            if (ret < 0 || oid != WC_PKCS12_DATA) {
                WOLFSSL_MSG("Not PKCS12 DATA object or get object parse error");
                freeBuffers(*pkey, buf, pkcs12->heap);
                freeCertList(certList, pkcs12->heap);
                return ASN_PARSE_E;
            }

            /* decrypted content overwrites input buffer */
            size = ci->dataSz - idx;
            buf = (byte*)XMALLOC(size, pkcs12->heap, DYNAMIC_TYPE_PKCS);
            if (buf == NULL) {
                freeBuffers(*pkey, buf, pkcs12->heap);
                freeCertList(certList, pkcs12->heap);
                return MEMORY_E;
            }
            XMEMCPY(buf, data + idx, size);

            if ((ret = DecryptContent(buf, size, psw, pswSz)) < 0) {
                freeBuffers(*pkey, buf, pkcs12->heap);
                freeCertList(certList, pkcs12->heap);
                WOLFSSL_MSG("Decryption failed, algorithm not compiled in?");
                return ret;
            }

            data = buf;
            idx = 0;
            #ifdef WOLFSSL_DEBUG_PKCS12
            {
                byte* p;
                for (printf("\tData = "), p = (byte*)buf;
                    p < (byte*)buf + size;
                    printf("%02X", *p), p++);
                printf("\n");
            }
            #endif
        }
        else { /* type DATA */
            WOLFSSL_MSG("Parsing PKCS12 DATA Content Info Container");
            data = ci->data;
            if (data[idx++] != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC)) {
                freeBuffers(*pkey, buf, pkcs12->heap);
                freeCertList(certList, pkcs12->heap);
                return ASN_PARSE_E;
            }
            if ((ret = GetLength(data, &idx, &size, ci->dataSz)) <= 0) {
                freeBuffers(*pkey, buf, pkcs12->heap);
                freeCertList(certList, pkcs12->heap);
                return ret;
            }
            if (data[idx++] != ASN_OCTET_STRING) {
                freeBuffers(*pkey, buf, pkcs12->heap);
                freeCertList(certList, pkcs12->heap);
                return ASN_PARSE_E;
            }
            if ((ret = GetLength(data, &idx, &size, ci->dataSz)) < 0) {
                freeBuffers(*pkey, buf, pkcs12->heap);
                freeCertList(certList, pkcs12->heap);
                return ret;
            }

        }

        /* parse through bags in ContentInfo */
        if ((ret = GetSequence(data, &idx, &totalSz, ci->dataSz)) < 0) {
            freeBuffers(*pkey, buf, pkcs12->heap);
            freeCertList(certList, pkcs12->heap);
            return ret;
        }
        totalSz += idx;

        while ((int)idx < totalSz) {
            int bagSz;
            if ((ret = GetSequence(data, &idx, &bagSz, ci->dataSz)) < 0) {
                freeBuffers(*pkey, buf, pkcs12->heap);
                freeCertList(certList, pkcs12->heap);
                return ret;
            }
            bagSz += idx;

            if ((ret = GetObjectId(data, &idx, &oid, oidIgnoreType,
                                                             ci->dataSz)) < 0) {
                freeBuffers(*pkey, buf, pkcs12->heap);
                freeCertList(certList, pkcs12->heap);
                return ret;
            }

            switch (oid) {
                case WC_PKCS12_KeyBag: /* 667 */
                    WOLFSSL_MSG("PKCS12 Key Bag found");
                    if (data[idx++] !=
                                     (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC)) {
                        freeBuffers(*pkey, buf, pkcs12->heap);
                        freeCertList(certList, pkcs12->heap);
                        return ASN_PARSE_E;
                    }
                    if ((ret = GetLength(data, &idx, &size, ci->dataSz)) <= 0) {
                        freeBuffers(*pkey, buf, pkcs12->heap);
                        freeCertList(certList, pkcs12->heap);
                        return ASN_PARSE_E;
                    }
                    if (*pkey == NULL) {
                        *pkey = (byte*)XMALLOC(size, pkcs12->heap,
                                                             DYNAMIC_TYPE_PKCS);
                        if (*pkey == NULL) {
                            freeBuffers(*pkey, buf, pkcs12->heap);
                            freeCertList(certList, pkcs12->heap);
                            return MEMORY_E;
                        }
                        XMEMCPY(*pkey, data + idx, size);
                        *pkeySz =  ToTraditional(*pkey, size);
                    }
                    #ifdef WOLFSSL_DEBUG_PKCS12
                        {
                            byte* p;
                            for (printf("\tKey = "), p = (byte*)*pkey;
                                p < (byte*)*pkey + size;
                                printf("%02X", *p), p++);
                            printf("\n");
                        }
                    #endif
                    idx += size;
                    break;

                case WC_PKCS12_ShroudedKeyBag: /* 668 */
                    {
                        byte* k;
                        WOLFSSL_MSG("PKCS12 Shrouded Key Bag found");
                        if (data[idx++] !=
                                     (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC)) {
                            freeBuffers(*pkey, buf, pkcs12->heap);
                            freeCertList(certList, pkcs12->heap);
                            return ASN_PARSE_E;
                        }
                        if ((ret = GetLength(data, &idx, &size,
                                                             ci->dataSz)) < 0) {
                            freeBuffers(*pkey, buf, pkcs12->heap);
                            freeCertList(certList, pkcs12->heap);
                            return ASN_PARSE_E;
                        }

                        k = (byte*)XMALLOC(size, pkcs12->heap,
                                                             DYNAMIC_TYPE_PKCS);
                        if (k == NULL) {
                            freeBuffers(*pkey, buf, pkcs12->heap);
                            freeCertList(certList, pkcs12->heap);
                            return MEMORY_E;
                        }
                        XMEMCPY(k, data + idx, size);

                        /* overwrites input, be warned */
                        if ((ret = ToTraditionalEnc(k, size, psw, pswSz)) < 0) {
                            freeBuffers(k, NULL, pkcs12->heap);
                            freeBuffers(*pkey, buf, pkcs12->heap);
                            freeCertList(certList, pkcs12->heap);
                            return ret;
                        }

                        if (ret < size) {
                            /* shrink key buffer */
                            k = (byte*)XREALLOC(k, ret, pkcs12->heap,
                                                             DYNAMIC_TYPE_PKCS);
                            if (k == NULL) {
                                freeBuffers(*pkey, buf, pkcs12->heap);
                                freeCertList(certList, pkcs12->heap);
                                return MEMORY_E;
                            }
                        }
                        size = ret;

                        if (*pkey == NULL) {
                            *pkey = k;
                            *pkeySz = size;
                        }
                        else { /* only expecting one key */
                            freeBuffers(k, NULL, pkcs12->heap);
                        }
                        idx += size;

                        #ifdef WOLFSSL_DEBUG_PKCS12
                        {
                            byte* p;
                            for (printf("\tKey = "), p = (byte*)k;
                                p < (byte*)k + ret;
                                printf("%02X", *p), p++);
                            printf("\n");
                        }
                        #endif
                    }
                    break;

                case WC_PKCS12_CertBag: /* 669 */
                {
                    WC_DerCertList* node;
                    WOLFSSL_MSG("PKCS12 Cert Bag found");
                    if (data[idx++] !=
                                     (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC)) {
                        freeBuffers(*pkey, buf, pkcs12->heap);
                        freeCertList(certList, pkcs12->heap);
                        return ASN_PARSE_E;
                    }
                    if ((ret = GetLength(data, &idx, &size, ci->dataSz)) < 0) {
                        freeBuffers(*pkey, buf, pkcs12->heap);
                        freeCertList(certList, pkcs12->heap);
                        return ret;
                    }

                    /* get cert bag type */
                    if ((ret = GetSequence(data, &idx, &size, ci->dataSz)) <0) {
                        freeBuffers(*pkey, buf, pkcs12->heap);
                        freeCertList(certList, pkcs12->heap);
                        return ret;
                    }

                    if ((ret = GetObjectId(data, &idx, &oid, oidIgnoreType,
                                                             ci->dataSz)) < 0) {
                        freeBuffers(*pkey, buf, pkcs12->heap);
                        freeCertList(certList, pkcs12->heap);
                        return ret;
                    }

                    switch (oid) {
                        case WC_PKCS12_CertBag_Type1:  /* 675 */
                            /* type 1 */
                            WOLFSSL_MSG("PKCS12 cert bag type 1");
                            if (data[idx++] !=
                                     (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC)) {
                                freeBuffers(*pkey, buf, pkcs12->heap);
                                freeCertList(certList, pkcs12->heap);
                                return ASN_PARSE_E;
                            }
                            if ((ret = GetLength(data, &idx, &size, ci->dataSz))
                                                                         <= 0) {
                                freeBuffers(*pkey, buf, pkcs12->heap);
                                freeCertList(certList, pkcs12->heap);
                                return ret;
                            }
                            if (data[idx++] != ASN_OCTET_STRING) {
                                freeBuffers(*pkey, buf, pkcs12->heap);
                                freeCertList(certList, pkcs12->heap);
                                return ASN_PARSE_E;
                            }
                            if ((ret = GetLength(data, &idx, &size, ci->dataSz))
                                                                          < 0) {
                                freeBuffers(*pkey, buf, pkcs12->heap);
                                freeCertList(certList, pkcs12->heap);
                                return ret;
                            }
                            break;
                       default:
                            WOLFSSL_MSG("Unknown PKCS12 cert bag type");
                    }

                    if (size + idx > (word32)bagSz) {
                        freeBuffers(*pkey, buf, pkcs12->heap);
                        freeCertList(certList, pkcs12->heap);
                        return ASN_PARSE_E;
                    }

                    /* list to hold all certs found */
                    node = (WC_DerCertList*)XMALLOC(sizeof(WC_DerCertList),
                                               pkcs12->heap, DYNAMIC_TYPE_PKCS);
                    if (node == NULL) {
                        freeBuffers(*pkey, buf, pkcs12->heap);
                        freeCertList(certList, pkcs12->heap);
                        return MEMORY_E;
                    }
                    XMEMSET(node, 0, sizeof(WC_DerCertList));

                    node->buffer = (byte*)XMALLOC(size, pkcs12->heap,
                                                             DYNAMIC_TYPE_PKCS);
                    if (node->buffer == NULL) {
                        XFREE(node, pkcs12->heap, DYNAMIC_TYPE_PKCS);
                        freeBuffers(*pkey, buf, pkcs12->heap);
                        freeCertList(certList, pkcs12->heap);
                        return MEMORY_E;
                    }
                    XMEMCPY(node->buffer, data + idx, size);
                    node->bufferSz = size;

                    /* put the new node into the list */
                    if (certList != NULL) {
                        WOLFSSL_MSG("Pushing new cert onto stack");
                        node->next = certList;
                        certList = node;
                    }
                    else {
                        certList = node;
                    }

                    /* on to next */
                    idx += size;
                }
                    break;

                case WC_PKCS12_CrlBag: /* 670 */
                    WOLFSSL_MSG("PKCS12 CRL BAG not yet supported");
                    break;

                case WC_PKCS12_SecretBag: /* 671 */
                    WOLFSSL_MSG("PKCS12 Secret BAG not yet supported");
                    break;

                case WC_PKCS12_SafeContentsBag: /* 672 */
                    WOLFSSL_MSG("PKCS12 Safe Contents BAG not yet supported");
                    break;

                default:
                    WOLFSSL_MSG("Unknown PKCS12 BAG type found");
            }

            /* Attribute, unknown bag or unsupported */
            if ((int)idx < bagSz) {
                idx = bagSz; /* skip for now */
            }
        }

        /* free temporary buffer */
        if (buf != NULL) {
            XFREE(buf, pkcs12->heap, DYNAMIC_TYPE_PKCS);
            buf = NULL;
        }
        ci = ci->next;
        WOLFSSL_MSG("Done Parsing PKCS12 Content Info Container");
    }

    /* check if key pair, remove from list */
    {
        WC_DerCertList* current  = certList;
        WC_DerCertList* previous = NULL;

        if (*pkey != NULL) {

        while (current != NULL) {
            DecodedCert DeCert;
            InitDecodedCert(&DeCert, current->buffer, current->bufferSz,
                                                                  pkcs12->heap);
            if (ParseCertRelative(&DeCert, CERT_TYPE, NO_VERIFY, NULL) == 0) {
                if (wc_CheckPrivateKey(*pkey, *pkeySz, &DeCert) == 1) {
                    WOLFSSL_MSG("Key Pair found");
                    *cert = current->buffer;
                    *certSz = current->bufferSz;

                    if (previous == NULL) {
                        certList = current->next;
                    }
                    else {
                        previous->next = current->next;
                    }
                    FreeDecodedCert(&DeCert);
                    XFREE(current, pkcs12->heap, DYNAMIC_TYPE_PKCS);
                    break;
                }
            }

            FreeDecodedCert(&DeCert);
            previous = current;
            current  = current->next;
        }

        }
    }

    if (ca != NULL) {
        *ca = certList;
    }
    else {
        /* free list, not wanted */
        freeCertList(certList, pkcs12->heap);
    }

    return 1;
}
bool	SimpleAudioDriver::start(IOService* inProvider)
{
	//	start the superclass
    bool theAnswer = IOService::start(inProvider);
    if(theAnswer)
	{
		//	create the work loop
		mWorkLoop = IOWorkLoop::workLoop();
		FailIfNULL(mWorkLoop, theAnswer = kIOReturnNoResources, Failure, "SimpleAudioDriver::start: couldn't allocate the work loop");
		
		//	create the command gate
		mCommandGate = IOCommandGate::commandGate(this);
		FailIfNULL(mWorkLoop, theAnswer = kIOReturnNoResources, Failure, "SimpleAudioDriver::start: couldn't allocate the command gate");
		
		//	attach it to the work loop
		mWorkLoop->addEventSource(mCommandGate);
		
		//	initialize the stuff tracked by the IORegistry
		mSampleRate = 44100;
		setProperty(kSimpleAudioDriver_RegistryKey_SampleRate, mSampleRate, sizeof(mSampleRate) * 8);
		
		mIOBufferFrameSize = 16384;
		setProperty(kSimpleAudioDriver_RegistryKey_RingBufferFrameSize, mIOBufferFrameSize, sizeof(mIOBufferFrameSize) * 8);
		
		char theDeviceUID[128];
		snprintf(theDeviceUID, 128, "SimpleAudioDevice-%d", static_cast<int>(random() % 100000));
		setProperty(kSimpleAudioDriver_RegistryKey_DeviceUID, theDeviceUID);

		//	allocate the IO buffers
		IOReturn theError = allocateBuffers();
		FailIfError(theError, theAnswer = false, Failure, "SimpleAudioDriver::start: allocating the buffers failed");
		
		//	initialize the timer that stands in for a real interrupt
		theError = initTimer();
		FailIfError(theError, freeBuffers(); theAnswer = false, Failure, "SimpleAudioDriver::start: initializing the timer failed");
		
		//	initialize the controls
		theError = initControls();
		FailIfError(theError, theAnswer = false, Failure, "SimpleAudioDriver::start: initializing the controls failed");
		
		//	publish ourselves
		registerService();
	}

    return theAnswer;

Failure:
	if(mCommandGate != NULL)
	{
		if(mWorkLoop != NULL)
		{
			mWorkLoop->removeEventSource(mCommandGate);
			mCommandGate->release();
			mCommandGate = NULL;
		}
	}
	
	if(mWorkLoop != NULL)
	{
		mWorkLoop->release();
		mWorkLoop = NULL;
	}
	
	freeBuffers();
	destroyTimer();
	
	return theAnswer;
}
Esempio n. 27
0
int main(int argc, char *argv[])
{
	
    /* pixels per worker */
    int ppw = 0;
	
	/* number of workers */
	int num_worker;
	
	/* pixels of the entire image */
	int dim;
	
    /* dimension of the entire image */
    int width,height;
	
    /* time variables */
    struct timeval tv1, tv2;
	
    /* Dimension of the partitioned image */
    int dimx = 0, dimy = 0;
	
    /* fit of the Gaussian */
    double fit[DIM_FIT];
	
    /* image representing Gaussian fit */
    unsigned char *image = NULL;
	
#ifdef PADDED
	/* buffer for the padded image */
	unsigned char *padded = NULL;
#endif	

#ifdef MODULE
	/* socket for the camera */
	int new_sock;
#endif
	
    /* local partition of the image*/
    unsigned char *partition;
	
	/* size of reduce buffer */
	int buffer_size = DIM_FIT * (DIM_FIT + 1);
	
    /* indexes */
    int i = 0;
	
    /* buffer for fit procedure */
    double *data = (double *) malloc( sizeof(double) * buffer_size );
    gsl_matrix_view matrice = gsl_matrix_view_array(data, DIM_FIT, DIM_FIT);
    gsl_vector_view vettore = gsl_vector_view_array(data + (DIM_FIT * DIM_FIT), DIM_FIT);
	
    /* output buffer of reduce */
    double *ret = (double *) malloc( sizeof(double) * buffer_size );
    gsl_matrix_view r_matrice = gsl_matrix_view_array(ret, DIM_FIT, DIM_FIT);
    gsl_vector_view r_vettore = gsl_vector_view_array(ret + (DIM_FIT * DIM_FIT), DIM_FIT);
	
	/*********************************************************************
	 INIT
	 *********************************************************************/	
	
	srand(time(NULL));
	/* in order to recover from an error */
	gsl_set_error_handler_off();
	
    /* Initialize of MPI */
    MPI_Init(&argc, &argv);
	
	/* Check the input parameters */
    if (argc != 3) {
		fprintf(stderr, "Invalid number of parameters: %d\n",argc);
		MPI_Abort(MPI_COMM_WORLD,MPI_ERR_ARG);
    }
    
    /* Every process takes their own rank */
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
	
    /* Total number of processes */
    MPI_Comm_size(MPI_COMM_WORLD, &p);
	
	/* Number of workers */ 
	num_worker = p - PS;
	
    if (my_rank == EMITTER) {
#if DEBUG
		printf("Emitter with rank %d\n", my_rank);
#endif
		
#ifdef MODULE
		new_sock = Connect();
		
		if (Read(new_sock, &width, sizeof(int)) < 0)
			error("Error reading the integers");
		if (Read(new_sock, &height, sizeof(int)) < 0)
			error("Error reading the integers");
		
		dim = width * height;
		image = (unsigned char *) malloc (dim);
		/* read from the socket */
		if (Read(new_sock, image, dim) < 0)
			error("Error reading from socket");
#else		
		/* an image representing the gaussian is created and returned
		 as a unsigned char matrix */
		width = atoi(argv[1]);
		height = atoi(argv[2]);
		/* y dimension of the image is adjusted (if needed) */
		while (height % num_worker != 0) height++;
		/* image is created */
		image = createImage(width, height);
#endif		
		/* parameters of the gaussian are estimated */
		initialization(image, width, height,fit);
		
#if DEBUG
		printf("Emitter survived init\n");
#endif	
		
    } 
	
	/* broadcast data of the image */
	MPI_Bcast(&width,1,MPI_INT,EMITTER,MPI_COMM_WORLD);
	MPI_Bcast(&height,1,MPI_INT,EMITTER,MPI_COMM_WORLD);
	MPI_Bcast(&fit,DIM_FIT,MPI_DOUBLE,EMITTER,MPI_COMM_WORLD);
	
	/* dimension of the local partition are determined and relative buffers
	 are initialized */  
	
	dim = width * height;
	dimx = width;
	dimy = height / num_worker;
    ppw = dimx * dimy;
    partition = (unsigned char *) malloc(sizeof(unsigned char) * ppw);
    initBuffers(ppw);
	
    /* if I am the emitter I take the time */
    if (my_rank == EMITTER)
		gettimeofday(&tv1, NULL);
	
#ifdef PADDED
	if (my_rank == EMITTER){
		padded =(unsigned char*) malloc(sizeof(unsigned char) * ppw * p);
		for (i=0; i < dim; i++){
			padded[i + ppw] = image[i];
		}
		for(i=0;i<DIM_FIT * (DIM_FIT + 1);i++){
			ret[i] = 0;
		}		
		free(image);
		image = padded;
	}	
#endif	
	
    /*********************************************************************
	 LOOP on ELEMENTS
     *********************************************************************/		
	
    for (i = 0; i < STREAMLENGTH; i++) {
		
		/* the emitter executes the scatter */
		MPI_Scatter(image, ppw, MPI_UNSIGNED_CHAR, partition, ppw, MPI_UNSIGNED_CHAR, EMITTER, MPI_COMM_WORLD);
		/* execute the procedure over my partition */		
		if(my_rank >= PS){
			procedure(partition, dimx, dimy , fit, matrice, vettore, dimy*(my_rank-PS));
		}
	
		/* execute the reduce of matrix and vector */
		MPI_Reduce(data, ret, buffer_size , MPI_DOUBLE, MPI_SUM, EMITTER, MPI_COMM_WORLD);
		
		if (my_rank == EMITTER) {
			/* adjust fit results */			
			postProcedure(r_matrice,r_vettore,fit);	
		}
		
		/* broadcast of the result */
		MPI_Bcast(fit, DIM_FIT, MPI_DOUBLE, EMITTER, MPI_COMM_WORLD);
		
#ifdef DEBUG
		if (my_rank == EMITTER) {
			printf("Image %d: %f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\n", i, fit[PAR_A], fit[PAR_X],
				   fit[PAR_Y], fit[PAR_SX], fit[PAR_SY], fit[PAR_a], fit[PAR_b], fit[PAR_c]);
		}
#endif
		
#ifdef MODULE
		if (my_rank == EMITTER && i < STREAMLENGTH - 1) {		
			/* new image is stored in buffer image of the emitter*/
#ifdef PADDED
			if (Read(new_sock, image + ppw, dim) < 0)
				error("Error reading from socket");
#else			
			if (Read(new_sock, image, dim) < 0)
				error("Error reading from socket");
#endif				
		}
#endif			
    }
	
    if (my_rank == EMITTER) {
		gettimeofday(&tv2, NULL);
		/* print the parallelism degree, data size and the completion time */
		printf("%d\t%d\t%ld\n", p, dim,  (tv2.tv_sec - tv1.tv_sec) * 1000000 + tv2.tv_usec - tv1.tv_usec);
    }
    
	freeBuffers();
    /* Finalize of MPI */
    MPI_Finalize();
    
    return 0;
}
TerrainTileEditable::~TerrainTileEditable()
{
	destoryGeometry();
    freeBuffers();
}
Esempio n. 29
0
File: com.c Progetto: 8l/insieme
int
main ( int argc, char *argv[] )
{
  int *messList = NULL;
  int testIdx, doTestLoop;
  int i;

  executableName = "com";

  MPI_Init ( &argc, &argv );
  MPI_Get_processor_name ( hostName, &i );

  /* Set global wsize and rank values */
  MPI_Comm_size ( MPI_COMM_WORLD, &wsize );
  MPI_Comm_rank ( MPI_COMM_WORLD, &rank );

  if ( !initAllTestTypeParams ( &testParams ) )
  {
    MPI_Finalize (  );
    exit ( 1 );
  }

  argStruct.testList = "Bidirectional, BidirAsync";

  if ( !processArgs ( argc, argv ) )
  {
    if ( rank == 0 )
      printUse (  );

    MPI_Finalize (  );
    exit ( 1 );
  }

  /* If using a source directory of process rank target files,
   * get the next appropriate file.
   */
  if ( targetDirectory != NULL && getNextTargetFile (  ) == 0 )
  {
    prestaAbort ( "Failed to open target file in target directory %s\n",
                  targetDirectory );
  }

  doTestLoop = 1;
  while ( doTestLoop )
  {
    if ( !setupTestListParams (  ) || !initAllTestTypeParams ( &testParams ) )
    {
      if ( rank == 0 )
        printUse (  );

      MPI_Finalize (  );
      exit ( 1 );
    }

#ifdef PRINT_ENV
    if ( rank == 0 )
      printEnv();
#endif

    printReportHeader (  );

    for ( testIdx = 0; testIdx < TYPETOT; testIdx++ )
    {
      if ( argStruct.testList == NULL
           || ( argStruct.testList != NULL
                && strstr ( argStruct.testList,
                            testParams[testIdx].name ) != NULL ) )
      {
        prestaRankDebug ( 0, "running test index %d\n", testIdx );
        runTest ( &testParams[testIdx] );
      }
    }

    if ( presta_check_data == 1 )
    {
      MPI_Reduce ( &presta_data_err_total, &presta_global_data_err_total,
                   1, MPI_LONG_LONG, MPI_SUM, 0, MPI_COMM_WORLD );
    }

    if ( targetDirectory == NULL || getNextTargetFile (  ) == 0 )
    {
      doTestLoop = 0;
    }
  }

  printSeparator (  );

  freeBuffers ( &testParams );
  free ( messList );

  MPI_Finalize (  );

  exit ( 0 );
}
	// Implementation of inherited interfaces
	void* ANativeWindowDisplayAdapter::allocateBuffer(int width, int height,
			const char* format, int &bytes, int numBufs) {
		LOG_FUNCTION_NAME;
		status_t err;
		int i = -1;
		const int lnumBufs = numBufs;
		mBufferHandleMap = new buffer_handle_t*[lnumBufs];
		mGrallocHandleMap = new IMG_native_handle_t*[lnumBufs];
		int undequeued = 0;
		GraphicBufferMapper &mapper = GraphicBufferMapper::get();
		Rect bounds;

		if (NULL == mANativeWindow) {
			return NULL;
		}

		// Set gralloc usage bits for window.
		err = mANativeWindow->set_usage(mANativeWindow, CAMHAL_GRALLOC_USAGE);
		if (err != 0) {
			LOGINFO("native_window_set_usage failed: %s (%d)", strerror(-err), -err);

			if (ENODEV == err) {
				LOGINFO("Preview surface abandoned!");
				mANativeWindow = NULL;
			}
			return NULL;
		}

		LOGINFO("Number of buffers set to ANativeWindow %d", numBufs);
		///Set the number of buffers needed for camera preview
		err = mANativeWindow->set_buffer_count(mANativeWindow, numBufs);
		if (err != 0) {
			LOGINFO("set_buffer_count failed: %s (%d)", strerror(-err), -err);

			if (ENODEV == err) {
				LOGINFO("Preview surface abandoned!");
				mANativeWindow = NULL;
			}

			return NULL;
		}
		LOGINFO("Configuring %d buffers for ANativeWindow", numBufs);
		mBufferCount = numBufs;

		// Set window geometry
		err = mANativeWindow->set_buffers_geometry(mANativeWindow,
				width,
				height,
				ANDROID_HAL_PIXEL_FORMAT_YCbCr_422_I
				); //current camera is YUYV,which same as YUY2

		if (err != 0) {
			LOGINFO("native_window_set_buffers_geometry failed: %s (%d)",
					strerror(-err), -err);

			if (ENODEV == err) {
				LOGINFO("Preview surface abandoned!");
				mANativeWindow = NULL;
			}

			return NULL;
		}

		///We just return the buffers from ANativeWindow, if the width and height are same, else (vstab, vnf case)
		///re-allocate buffers using ANativeWindow and then get them
		///@todo - Re-allocate buffers for vnf and vstab using the width, height, format, numBufs etc
		if (mBufferHandleMap == NULL) {
			LOGINFO("Couldn't create array for ANativeWindow buffers");
			LOG_FUNCTION_NAME_EXIT;
			return NULL;
		}
		bytes = getBufSize(format, width, height);

		mANativeWindow->get_min_undequeued_buffer_count(mANativeWindow, &undequeued);
		LOGINFO("mBufferCount %d, undequeued %d\n", mBufferCount, undequeued);

		// lock the initial queueable buffers
		bounds.left = 0;
		bounds.top = 0;
		bounds.right = width;
		bounds.bottom = height;

		for (i = 0; i < mBufferCount; i++) {
			buffer_handle_t* buf;
			int stride;
			void * y_uv = NULL;

			err = mANativeWindow->dequeue_buffer(mANativeWindow, &buf, &stride);

			if (err != 0) {
				LOGINFO("dequeueBuffer failed: %s (%d)", strerror(-err), -err);
				if (ENODEV == err) {
					LOGINFO("Preview surface abandoned!");
					mANativeWindow = NULL;
				}
				goto fail;
			}

			mBufferHandleMap[i] = buf;

			//if(i < mBufferCount - undequeued){
			if(true){
				mapper.lock((buffer_handle_t) *mBufferHandleMap[i], CAMHAL_GRALLOC_USAGE, bounds, &y_uv);
				mGrallocHandleMap[i] = (IMG_native_handle_t*)y_uv;
				mANativeWindow->lock_buffer(mANativeWindow, mBufferHandleMap[i]);
				mFramesWithCameraAdapterMap.add((int) mGrallocHandleMap[i], i);
				mFrameProvider->addFramePointers((void*)mGrallocHandleMap[i] , NULL);
			}
			else{
				mANativeWindow->cancel_buffer(mANativeWindow, mBufferHandleMap[i]);
				//mFramesWithCameraAdapterMap.removeItem((int) mGrallocHandleMap[i]);
				mapper.unlock((buffer_handle_t) *mBufferHandleMap[i]);
			}
		}

		mFirstInit = true;
		mPixelFormat = getPixFormatConstant(format);
		mFrameWidth = width;
		mFrameHeight = height;

		return mGrallocHandleMap;

fail:
		// need to cancel buffers if any were dequeued
		for (int start = 0; start < i && i > 0; start++) {
			int err = mANativeWindow->cancel_buffer(mANativeWindow,
					mBufferHandleMap[start]);
			if (err != 0) {
				LOGINFO("cancelBuffer failed w/ error 0x%08x", err);
				break;
			}
			mFramesWithCameraAdapterMap.removeItem((int) mGrallocHandleMap[start]);
		}

		freeBuffers(mGrallocHandleMap);

		LOGINFO("Error occurred, performing cleanup");

		if (NULL != mErrorNotifier.get()) {
			mErrorNotifier->errorNotify(-ENOMEM);
		}

		LOG_FUNCTION_NAME_EXIT;
		return NULL;

	}