Beispiel #1
0
int learnImage(const char * filename ,unsigned int numberOfHorizontalTiles,unsigned int numberOfVerticalTiles)
{
   struct Image * inputImage = readImage(filename,guessFilenameTypeStupid(filename),0);
   if (inputImage!=0)
   {
     unsigned int tileWidth =inputImage->width/numberOfHorizontalTiles;
     unsigned int tileHeight=inputImage->height/numberOfVerticalTiles;
     fprintf(stderr,"Sucessfully opened image ( %ux%u ) , each tile is %ux%u ..\n",inputImage->width,inputImage->height,tileWidth,tileHeight);


     unsigned int x,y,i=0;
     for (y=0; y<numberOfVerticalTiles; y++)
     {
      for (x=0; x<numberOfHorizontalTiles; x++)
      {
        struct Image * part = createImageBitBlt(inputImage,x*tileWidth , y*tileHeight , tileWidth, tileHeight);
        if (part!=0)
        {
          char tileString[512]={0};
          snprintf(tileString,512,"tile-%05d.jpg",i);
          writeImageFile(part,JPG_CODEC,tileString);
          destroyImage(part);
        }
       ++i;
      }
     }


     destroyImage(inputImage);
     return 1;
   }
  return 0;
}
Beispiel #2
0
static void
free_image(Display * display, imagestruct * ip)
{
	if (ip->icons != NULL) {
		free(ip->icons);
		ip->icons = (imagetype *) NULL;
	}
	freeLogo(display, ip);
	if (ip->logo != None) {
		destroyImage(&ip->logo, &ip->graphics_format);
		ip->logo = None;
	}
	if (ip->fgGC != None) {
		XFreeGC(display, ip->fgGC);
		ip->fgGC = None;
	}
	if (ip->bgGC) {
		XFreeGC(display, ip->bgGC);
		ip->bgGC = None;
	}
	if (ip->pixmap) {
		XFreePixmap(display, ip->pixmap);
		ip->pixmap = None;
	}
}
Beispiel #3
0
void Display::terminate()
{
    makeCurrent(nullptr, nullptr, nullptr);

    while (!mContextSet.empty())
    {
        destroyContext(*mContextSet.begin());
    }

    while (!mImageSet.empty())
    {
        destroyImage(*mImageSet.begin());
    }

    while (!mImplementation->getSurfaceSet().empty())
    {
        destroySurface(*mImplementation->getSurfaceSet().begin());
    }

    mConfigSet.clear();

    if (mDevice != nullptr && mDevice->getOwningDisplay() != nullptr)
    {
        // Don't delete the device if it was created externally using eglCreateDeviceANGLE
        // We also shouldn't set it to null in case eglInitialize() is called again later
        SafeDelete(mDevice);
    }

    mImplementation->terminate();

    mInitialized = false;

    // Never de-init default platform.. terminate is not that final.
}
 /*
  * destroy window
  */
 void fastViewer::destroyWindow() {
   destroyImage();
   if (display_info.win != 0) {
     XFreeGC(display_info.display,display_info.gc);
     XDestroyWindow(display_info.display,display_info.win);
   }
   display_info.win = 0;
 }
Beispiel #5
0
int AmmCaptcha_getCaptchaFrame(unsigned int captchaID, char *mem,unsigned long * mem_size)
{
  struct Image * captcha = createImage(300,70,3);
  RenderString(captcha,&fontRAW, 0 + rand()%200 ,  rand()%40, hashMap_GetKeyAtIndex(captchaStrings,convertExternalIDToInternal(captchaID)));

  //Apply Swirling effect!
  coolPHPWave(captcha, 11,12,5,14);

  //WriteJPEGFile(captcha,"captcha.jpg");
  WriteJPEGMemory(captcha,mem,mem_size);
  fprintf(stderr,"Survived WriteJPEG");
  destroyImage(captcha);
  fprintf(stderr,"Survived destroyImage");
  return 1;
}
Beispiel #6
0
static void
free_puzzle(Display * display, puzzlestruct * pp)
{
	if (pp->fixbuff != NULL) {
		free(pp->fixbuff);
		pp->fixbuff = (int *) NULL;
	}
	if (pp->bufferBox != None) {
		XFreePixmap(display, pp->bufferBox);
		pp->bufferBox = None;
	}
	free_stuff(display, pp);
	if (pp->logo != None) {
		destroyImage(&pp->logo, &pp->graphics_format);
		pp->logo = None;
	}
}
Beispiel #7
0
static void
free_life1d(Display * display, life1dstruct * lp)
{
	int         shade;

	if (lp->stippledGC != None) {
		XFreeGC(display, lp->stippledGC);
		lp->stippledGC = None;
	}
	if (lp->init_bits != 0) {
		for (shade = 0; shade < MAXSTATES; shade++)
			XFreePixmap(display, lp->pixmaps[shade]);
		lp->init_bits = 0;
	}
	if (lp->newcells != NULL) {
		free(lp->newcells);
		lp->newcells = (unsigned char *) NULL;
	}
	if (lp->oldcells != NULL) {
		free(lp->oldcells);
		lp->oldcells = (unsigned char *) NULL;
	}
	if (lp->buffer != NULL) {
		free(lp->buffer);
		lp->buffer = (unsigned char *) NULL;
	}
	if (lp->previousBuffer != NULL) {
		free(lp->previousBuffer);
		lp->previousBuffer = (unsigned char *) NULL;
	}
	if (lp->nextstate != NULL) {
		free(lp->nextstate);
		lp->nextstate = (char *) NULL;
	}
	free_stuff(display, lp);
	if (lp->logo != None) {
		destroyImage(&lp->logo, &lp->graphics_format);
		lp->logo = None;
	}
}
Beispiel #8
0
void Display::terminate()
{
    makeCurrent(nullptr, nullptr, nullptr);

    while (!mContextSet.empty())
    {
        destroyContext(*mContextSet.begin());
    }

    while (!mImageSet.empty())
    {
        destroyImage(*mImageSet.begin());
    }

    mConfigSet.clear();

    mImplementation->terminate();

    mInitialized = false;

    // Never de-init default platform.. terminate is not that final.
}
Beispiel #9
0
void
destroyWorms(
    WORMS_T *worms)
{
    uint16_t i = 0;
    for (i = 0 ; i < worms->size ; i++)
    {
        WORM_T *worm = &(worms->worms[i]);
        destroyWorm(worm);
    }

    free(worms->worms);

    worms->size = 0;
    worms->worms = NULL;

    destroyImage(&(worms->image));


    //---------------------------------------------------------------------

    int result = 0;

    DISPMANX_UPDATE_HANDLE_T update = vc_dispmanx_update_start(0);
    assert(update != 0);
    result = vc_dispmanx_element_remove(update, worms->element);
    assert(result == 0);
    result = vc_dispmanx_update_submit_sync(update);
    assert(result == 0);

    //---------------------------------------------------------------------

    result = vc_dispmanx_resource_delete(worms->frontResource);
    assert(result == 0);
    result = vc_dispmanx_resource_delete(worms->backResource);
    assert(result == 0);
}
int runFilter(int argc, char *argv[])
{
 char * filenameInput=argv[1];
 char * filenameOutput=argv[2];
 unsigned int inputType = guessFilenameTypeStupid(filenameInput);
 struct Image * inputImage = readImage(filenameInput,inputType,0);
 struct Image * outputImage = 0; //This will get allocated when and if needed

 if (inputImage!=0)
 {
    unsigned int outputType = guessFilenameTypeStupid(filenameOutput);
    unsigned int i=0;
      for (i=0; i<argc; i++)
      {

        if ( strcmp(argv[i],"--learn")==0 )
        {
          destroyImage(inputImage);
          learnImage(filenameInput,atoi(argv[i+1]),atoi(argv[i+2]));
          exit(0);
        } else
        if ( strcmp(argv[i],"--rgbcube")==0 )
        {
          unsigned int dim=32;
          unsigned char R = (char) atoi(argv[i]+1);
          unsigned char G = (char) atoi(argv[i]+2);
          unsigned char B = (char) atoi(argv[i]+3);

          outputImage = createImage( dim , dim , 3 , 8 );


           bitbltColorRGB(outputImage->pixels ,   0  ,  0 , dim , dim ,  R ,  G ,  B , dim-1 , dim-1);

           writeImageFile(outputImage,PPM_CODEC ,"new_mX.pnm");
           writeImageFile(outputImage,PPM_CODEC ,"new_pX.pnm");
           writeImageFile(outputImage,PPM_CODEC ,"new_mY.pnm");
           writeImageFile(outputImage,PPM_CODEC ,"new_pY.pnm");
           writeImageFile(outputImage,PPM_CODEC ,"new_mZ.pnm");
           writeImageFile(outputImage,PPM_CODEC ,"new_pZ.pnm");
          destroyImage(outputImage);

        } else
        if ( strcmp(argv[i],"--envcube")==0 )
        {
          fprintf(stdout,"Converting Environment Cube \n");
          unsigned int outputType = guessFilenameTypeStupid(filenameOutput);
          //outputImage = createSameDimensionsImage(inputImage);

          unsigned int outputWidth = inputImage->width;
          unsigned int outputHeight = (unsigned int ) (3*inputImage->width)/4;
          outputImage = createImage( outputWidth , outputHeight , 3 , 8 );

         createCubeMapFace(  outputImage->pixels ,  outputImage->width , outputImage->height , outputImage->channels , outputImage->bitsperpixel ,
                             inputImage->pixels ,  inputImage->width , inputImage->height , inputImage->channels , inputImage->bitsperpixel
                          );


         struct Image * partImg=0;
         unsigned int outX=0 , outY=0 , outWidth=0 , outHeight=0;
         getCubeMap2DCoords(outputWidth,outputHeight, /*x*/ -1 , /*y*/  0  , /*z*/  0 , &outX , &outY , &outWidth , &outHeight );
         partImg=createImageBitBlt( outputImage , outX , outY , outWidth , outHeight );
         writeImageFile(partImg,PPM_CODEC ,"new_mX.pnm"); destroyImage(partImg);

         getCubeMap2DCoords(outputWidth,outputHeight, /*x*/  1 , /*y*/  0  , /*z*/  0 , &outX , &outY , &outWidth , &outHeight );
         partImg=createImageBitBlt( outputImage , outX , outY , outWidth , outHeight );
         writeImageFile(partImg,PPM_CODEC ,"new_pX.pnm"); destroyImage(partImg);

         getCubeMap2DCoords(outputWidth,outputHeight, /*x*/  0 , /*y*/ -1  , /*z*/  0 , &outX , &outY , &outWidth , &outHeight );
         partImg=createImageBitBlt( outputImage , outX , outY , outWidth , outHeight );
         writeImageFile(partImg,PPM_CODEC ,"new_mY.pnm"); destroyImage(partImg);

         getCubeMap2DCoords(outputWidth,outputHeight, /*x*/  0 , /*y*/  1  , /*z*/  0 , &outX , &outY , &outWidth , &outHeight );
         partImg=createImageBitBlt( outputImage , outX , outY , outWidth , outHeight );
         writeImageFile(partImg,PPM_CODEC ,"new_pY.pnm"); destroyImage(partImg);

         getCubeMap2DCoords(outputWidth,outputHeight, /*x*/  0 , /*y*/  0  , /*z*/ -1 , &outX , &outY , &outWidth , &outHeight );
         partImg=createImageBitBlt( outputImage , outX , outY , outWidth , outHeight );
         writeImageFile(partImg,PPM_CODEC ,"new_mZ.pnm"); destroyImage(partImg);

         getCubeMap2DCoords(outputWidth,outputHeight, /*x*/  0 , /*y*/  0  , /*z*/  1 , &outX , &outY , &outWidth , &outHeight );
         partImg=createImageBitBlt( outputImage , outX , outY , outWidth , outHeight );
         writeImageFile(partImg,PPM_CODEC ,"new_pZ.pnm"); destroyImage(partImg);
        } else
        if ( strcmp(argv[i],"--compare")==0 )
        {
          unsigned int outputType = guessFilenameTypeStupid(filenameOutput);
          outputImage = readImage(filenameOutput,outputType ,0);

          float noise = calculatePSNR( outputImage->pixels ,  outputImage->width , outputImage->height , outputImage->channels ,
                                       inputImage->pixels ,  inputImage->width , inputImage->height , inputImage->channels );

           fprintf(stdout,"Compared Detected Noise is %0.4f dB \n",noise);
           exit(0);
        } else
        if ( strcmp(argv[i],"--gaussian")==0 )
        {
          monochrome(inputImage);
          outputImage = createSameDimensionsImage(inputImage);

         unsigned int normalizeGaussianKernel=1;
         unsigned int kernelWidth=5;
         unsigned int kernelHeight=5;
         float * convolutionMatrix=allocateGaussianKernel(kernelWidth,kernelHeight,normalizeGaussianKernel);
         float divisor=1.0;

         float * inF = copyUCharImage2Float(inputImage->pixels ,  inputImage->width , inputImage->height , inputImage->channels );
         float * outF = (float*) malloc(sizeof(float) *  outputImage->width * outputImage->height *  outputImage->channels );


         convolutionFilter1ChF(
                                 outF ,  outputImage->width , outputImage->height ,
                                 inF,  inputImage->width , inputImage->height ,
                                 convolutionMatrix , kernelWidth , kernelHeight , &divisor
                              );


         free(convolutionMatrix);

         castFloatImage2UChar(outputImage->pixels, outF, outputImage->width , outputImage->height ,  outputImage->channels );
         free(inF);
         free(outF);
        } else
        if ( strcmp(argv[i],"--ctbilateral")==0 )
        {
          monochrome(inputImage);
          outputImage = createSameDimensionsImage(inputImage);

          float sigma = atof(argv[i+1]);
          constantTimeBilateralFilter(
                                       inputImage->pixels  ,  inputImage->width , inputImage->height , inputImage->channels ,
                                       outputImage->pixels ,  outputImage->width , outputImage->height
                                      ,&sigma //sigma
                                      ,atoi(argv[i+2]) //bins
                                      ,atoi(argv[i+3]) //useDeriche
                                     );

        } else
        if ( strcmp(argv[i],"--deriche")==0 )
        {
          monochrome(inputImage);
          outputImage = createSameDimensionsImage(inputImage);
          float sigma = atof(argv[i+1]);
          dericheRecursiveGaussianGray( outputImage->pixels ,  outputImage->width , outputImage->height , inputImage->channels ,
                                        inputImage->pixels ,  inputImage->width , inputImage->height ,
                                        &sigma , atoi(argv[i+2])
                                       );
        } else
        if ( strcmp(argv[i],"--dericheF")==0 )
        {
          fprintf(stderr,"This is a test call for casting code , this shouldnt be normally used..\n");
          monochrome(inputImage);
          outputImage = createSameDimensionsImage(inputImage);
          float sigma = atof(argv[i+1]);

          //outputImage = copyImage(inputImage);
         float * inF = copyUCharImage2Float(inputImage->pixels ,  inputImage->width , inputImage->height , inputImage->channels );
         float * outF = (float*) malloc(sizeof(float) *  outputImage->width * outputImage->height *  outputImage->channels );

         dericheRecursiveGaussianGrayF(  outF  ,  outputImage->width , outputImage->height ,  inputImage->channels ,
                                         inF ,  inputImage->width , inputImage->height  ,
                                         &sigma , atoi(argv[i+2])
                                        );

         castFloatImage2UChar(outputImage->pixels, outF, outputImage->width , outputImage->height ,  outputImage->channels );
         free(inF);
         free(outF);
        } else
        if ( strcmp(argv[i],"--median")==0 )
        {
           outputImage = copyImage(inputImage);
           medianFilter3ch(
                         outputImage->pixels ,  outputImage->width , outputImage->height ,
                         inputImage->pixels ,  inputImage->width , inputImage->height  ,
                         atoi(argv[i+1]) , atoi(argv[i+2])
                        );
        } else
        if ( strcmp(argv[i],"--meansat")==0 )
        {
           outputImage = copyImage(inputImage);
           meanFilterSAT(
                         outputImage->pixels ,  outputImage->width , outputImage->height , outputImage->channels ,
                         inputImage->pixels ,  inputImage->width , inputImage->height , inputImage->channels ,
                         atoi(argv[i+1]) , atoi(argv[i+2])
                        );
        } else
        if ( strcmp(argv[i],"--monochrome")==0 )
        {
          outputImage = copyImage(inputImage);
          monochrome(outputImage);
        } else
        if ( strcmp(argv[i],"--bilateral")==0 )
        {
          outputImage = copyImage(inputImage);
          bilateralFilter( outputImage->pixels ,  outputImage->width , outputImage->height ,
                           inputImage->pixels ,  inputImage->width , inputImage->height ,
                            atof(argv[i+1]) , atof(argv[i+2]) , atoi(argv[i+3])
                         );
        } else
        if ( strcmp(argv[i],"--contrast")==0 )
        {
          outputImage = copyImage(inputImage);
          contrast(outputImage,atof(argv[i+1]));
        } else
        if ( strcmp(argv[i],"--sattest")==0 )
        {
            float * tmp = allocateGaussianKernel(3,5.0,1);
            if (tmp!=0) { free(tmp); }

            tmp = allocateGaussianKernel(9,5.0,1);
            if (tmp!=0) { free(tmp); }


            tmp = allocateGaussianKernel(15,5.0,1);
            if (tmp!=0) { free(tmp); }


            summedAreaTableTest();
            unsigned int * integralImageOutput = 0;
            integralImageOutput = generateSummedAreaTableRGB(inputImage->pixels ,  inputImage->width , inputImage->height);
            if (integralImageOutput!=0)
            {
              free(integralImageOutput);
              fprintf(stderr,"integralImage test was successful\n");
            }
        }
      }

    writeImageFile(outputImage,outputType ,filenameOutput);
    destroyImage(outputImage);
    destroyImage(inputImage);
    return 1;
 }
 return 0;
}
Beispiel #11
0
void LayerTreeHostProxy::syncRemoteContent()
{
    // We enqueue messages and execute them during paint, as they require an active GL context.
    ensureRootLayer();

    while (OwnPtr<LayerTreeMessageToRenderer> nextMessage = m_messagesToRenderer.tryGetMessage()) {
        switch (nextMessage->type()) {
        case LayerTreeMessageToRenderer::SetRootLayer: {
            const SetRootLayerMessageData& data = static_cast<SetRootLayerMessage*>(nextMessage.get())->data();
            setRootLayerID(data.layerID);
            break;
        }

        case LayerTreeMessageToRenderer::DeleteLayer: {
            const DeleteLayerMessageData& data = static_cast<DeleteLayerMessage*>(nextMessage.get())->data();
            deleteLayer(data.layerID);
            break;
        }

        case LayerTreeMessageToRenderer::SyncLayerParameters: {
            const SyncLayerParametersMessageData& data = static_cast<SyncLayerParametersMessage*>(nextMessage.get())->data();
            syncLayerParameters(data.layerInfo);
            break;
        }

        case LayerTreeMessageToRenderer::CreateTile: {
            const CreateTileMessageData& data = static_cast<CreateTileMessage*>(nextMessage.get())->data();
            createTile(data.layerID, data.remoteTileID, data.scale);
            break;
        }

        case LayerTreeMessageToRenderer::RemoveTile: {
            const RemoveTileMessageData& data = static_cast<RemoveTileMessage*>(nextMessage.get())->data();
            removeTile(data.layerID, data.remoteTileID);
            break;
        }

        case LayerTreeMessageToRenderer::UpdateTile: {
            const UpdateTileMessageData& data = static_cast<UpdateTileMessage*>(nextMessage.get())->data();
            updateTile(data.layerID, data.remoteTileID, data.sourceRect, data.targetRect, data.image);
            break;
        }

        case LayerTreeMessageToRenderer::CreateImage: {
            const CreateImageMessageData& data = static_cast<CreateImageMessage*>(nextMessage.get())->data();
            createImage(data.imageID, data.image);
            break;
        }

        case LayerTreeMessageToRenderer::DestroyImage: {
            const CreateImageMessageData& data = static_cast<CreateImageMessage*>(nextMessage.get())->data();
            destroyImage(data.imageID);
            break;
        }

        case LayerTreeMessageToRenderer::FlushLayerChanges:
            flushLayerChanges();
            break;
        }
    }
}
Beispiel #12
0
int main(int argc, char** argv)
{
    DecodeInput *input;
    int32_t fd = -1;
    int32_t i = 0;
    int32_t ioctlRet = -1;
    YamiMediaCodec::CalcFps calcFps;

    renderMode = 3; // set default render mode to 3

    yamiTraceInit();
#if __ENABLE_V4L2_GLX__
    XInitThreads();
#endif

#if __ENABLE_V4L2_OPS__
    // FIXME, use libv4l2codec_hw.so instead
    if (!loadV4l2CodecDevice("libyami_v4l2.so")) {
        ERROR("fail to init v4l2codec device with __ENABLE_V4L2_OPS__\n");
        return -1;
    }
#endif

    if (!process_cmdline(argc, argv))
        return -1;

    if (!inputFileName) {
        ERROR("no input media file specified\n");
        return -1;
    }
    INFO("input file: %s, renderMode: %d", inputFileName, renderMode);

    if (!dumpOutputName)
        dumpOutputName = strdup ("./");

#if !__ENABLE_V4L2_GLX__
    switch (renderMode) {
    case 0:
        memoryType = VIDEO_DATA_MEMORY_TYPE_RAW_COPY;
        memoryTypeStr = typeStrRawData;
    break;
    case 3:
        memoryType = VIDEO_DATA_MEMORY_TYPE_DRM_NAME;
        memoryTypeStr = typeStrDrmName;
    break;
    case 4:
        memoryType = VIDEO_DATA_MEMORY_TYPE_DMA_BUF;
        memoryTypeStr = typeStrDmaBuf;
    break;
    default:
        ASSERT(0 && "unsupported render mode, -m [0,3,4] are supported");
    break;
    }
#endif

    input = DecodeInput::create(inputFileName);
    if (input==NULL) {
        ERROR("fail to init input stream\n");
        return -1;
    }

    renderFrameCount = 0;
    calcFps.setAnchor();
    // open device
    fd = SIMULATE_V4L2_OP(Open)("decoder", 0);
    ASSERT(fd!=-1);

#ifdef ANDROID
#elif __ENABLE_V4L2_GLX__
    x11Display = XOpenDisplay(NULL);
    ASSERT(x11Display);
    ioctlRet = SIMULATE_V4L2_OP(SetXDisplay)(fd, x11Display);
#endif
    // set output frame memory type
#if __ENABLE_V4L2_OPS__
    SIMULATE_V4L2_OP(SetParameter)(fd, "frame-memory-type", memoryTypeStr);
#elif !__ENABLE_V4L2_GLX__
    SIMULATE_V4L2_OP(FrameMemoryType)(fd, memoryType);
#endif

    // query hw capability
    struct v4l2_capability caps;
    memset(&caps, 0, sizeof(caps));
    caps.capabilities = V4L2_CAP_VIDEO_CAPTURE_MPLANE | V4L2_CAP_VIDEO_OUTPUT_MPLANE | V4L2_CAP_STREAMING;
    ioctlRet = SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_QUERYCAP, &caps);
    ASSERT(ioctlRet != -1);

    // set input/output data format
    uint32_t codecFormat = v4l2PixelFormatFromMime(input->getMimeType());
    if (!codecFormat) {
        ERROR("unsupported mimetype, %s", input->getMimeType());
        return -1;
    }

    struct v4l2_format format;
    memset(&format, 0, sizeof(format));
    format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
    format.fmt.pix_mp.pixelformat = codecFormat;
    format.fmt.pix_mp.num_planes = 1;
    format.fmt.pix_mp.plane_fmt[0].sizeimage = k_maxInputBufferSize;
    ioctlRet = SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_S_FMT, &format);
    ASSERT(ioctlRet != -1);

    // set preferred output format
    memset(&format, 0, sizeof(format));
    format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    uint8_t* data = (uint8_t*)input->getCodecData().data();
    uint32_t size = input->getCodecData().size();
    //save codecdata, size+data, the type of format.fmt.raw_data is __u8[200]
    //we must make sure enough space (>=sizeof(uint32_t) + size) to store codecdata
    memcpy(format.fmt.raw_data, &size, sizeof(uint32_t));
    if(sizeof(format.fmt.raw_data) >= size + sizeof(uint32_t))
        memcpy(format.fmt.raw_data + sizeof(uint32_t), data, size);
    else {
        ERROR("No enough space to store codec data");
        return -1;
    }
    ioctlRet = SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_S_FMT, &format);
    ASSERT(ioctlRet != -1);

    // input port starts as early as possible to decide output frame format
    __u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
    ioctlRet = SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_STREAMON, &type);
    ASSERT(ioctlRet != -1);

    // setup input buffers
    struct v4l2_requestbuffers reqbufs;
    memset(&reqbufs, 0, sizeof(reqbufs));
    reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
    reqbufs.memory = V4L2_MEMORY_MMAP;
    reqbufs.count = 2;
    ioctlRet = SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_REQBUFS, &reqbufs);
    ASSERT(ioctlRet != -1);
    ASSERT(reqbufs.count>0);
    inputQueueCapacity = reqbufs.count;
    inputFrames.resize(inputQueueCapacity);

    for (i=0; i<inputQueueCapacity; i++) {
        struct v4l2_plane planes[k_inputPlaneCount];
        struct v4l2_buffer buffer;
        memset(&buffer, 0, sizeof(buffer));
        memset(planes, 0, sizeof(planes));
        buffer.index = i;
        buffer.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
        buffer.memory = V4L2_MEMORY_MMAP;
        buffer.m.planes = planes;
        buffer.length = k_inputPlaneCount;
        ioctlRet = SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_QUERYBUF, &buffer);
        ASSERT(ioctlRet != -1);

        // length and mem_offset should be filled by VIDIOC_QUERYBUF above
        void* address = SIMULATE_V4L2_OP(Mmap)(NULL,
                                      buffer.m.planes[0].length,
                                      PROT_READ | PROT_WRITE,
                                      MAP_SHARED, fd,
                                      buffer.m.planes[0].m.mem_offset);
        ASSERT(address);
        inputFrames[i] = static_cast<uint8_t*>(address);
        DEBUG("inputFrames[%d] = %p", i, inputFrames[i]);
    }

    // feed input frames first
    for (i=0; i<inputQueueCapacity; i++) {
        if (!feedOneInputFrame(input, fd, i)) {
            break;
        }
    }

    // query video resolution
    memset(&format, 0, sizeof(format));
    format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    while (1) {
        if (SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_G_FMT, &format) != 0) {
            if (errno != EINVAL) {
                // EINVAL means we haven't seen sufficient stream to decode the format.
                INFO("ioctl() failed: VIDIOC_G_FMT, haven't get video resolution during start yet, waiting");
            }
        } else {
            break;
        }
        usleep(50);
    }
    outputPlaneCount = format.fmt.pix_mp.num_planes;
    ASSERT(outputPlaneCount == 2);
    videoWidth = format.fmt.pix_mp.width;
    videoHeight = format.fmt.pix_mp.height;
    ASSERT(videoWidth && videoHeight);

#ifdef ANDROID
    __u32 pixelformat = format.fmt.pix_mp.pixelformat;
    if (!createNativeWindow(pixelformat)) {
        fprintf(stderr, "create native window error\n");
        return -1;
    }

    int minUndequeuedBuffs = 0;
    status_t err = mNativeWindow->query(mNativeWindow.get(), NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBuffs);
    if (err != 0) {
        fprintf(stderr, "query native window min undequeued buffers error\n");
        return err;
    }
#endif

    // setup output buffers
    // Number of output buffers we need.
    struct v4l2_control ctrl;
    memset(&ctrl, 0, sizeof(ctrl));
    ctrl.id = V4L2_CID_MIN_BUFFERS_FOR_CAPTURE;
    ioctlRet = SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_G_CTRL, &ctrl);
#ifndef ANDROID
    uint32_t minOutputFrameCount = ctrl.value + k_extraOutputFrameCount;
#else
    uint32_t minOutputFrameCount = ctrl.value + k_extraOutputFrameCount + minUndequeuedBuffs;
#endif

    memset(&reqbufs, 0, sizeof(reqbufs));
    reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    reqbufs.memory = V4L2_MEMORY_MMAP;
    reqbufs.count = minOutputFrameCount;
    ioctlRet = SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_REQBUFS, &reqbufs);
    ASSERT(ioctlRet != -1);
    ASSERT(reqbufs.count>0);
    outputQueueCapacity = reqbufs.count;

#ifdef ANDROID
#elif __ENABLE_V4L2_GLX__
    x11Window = XCreateSimpleWindow(x11Display, DefaultRootWindow(x11Display)
        , 0, 0, videoWidth, videoHeight, 0, 0
        , WhitePixel(x11Display, 0));
    XMapWindow(x11Display, x11Window);
    pixmaps.resize(outputQueueCapacity);
    glxPixmaps.resize(outputQueueCapacity);
    textureIds.resize(outputQueueCapacity);

    if (!glxContext) {
        glxContext = glxInit(x11Display, x11Window);
    }
    ASSERT(glxContext);

    glGenTextures(outputQueueCapacity, &textureIds[0] );
    for (i=0; i<outputQueueCapacity; i++) {
        int ret = createPixmapForTexture(glxContext, textureIds[i], videoWidth, videoHeight, &pixmaps[i], &glxPixmaps[i]);
        DEBUG("textureIds[%d]: 0x%x, pixmaps[%d]=0x%lx, glxPixmaps[%d]: 0x%lx", i, textureIds[i], i, pixmaps[i], i, glxPixmaps[i]);
        ASSERT(ret == 0);
        ret = SIMULATE_V4L2_OP(UsePixmap)(fd, i, pixmaps[i]);
        ASSERT(ret == 0);
    }
#else
    if (IS_RAW_DATA()) {
        rawOutputFrames.resize(outputQueueCapacity);
        for (i=0; i<outputQueueCapacity; i++) {
            struct v4l2_plane planes[k_maxOutputPlaneCount];
            struct v4l2_buffer buffer;
            memset(&buffer, 0, sizeof(buffer));
            memset(planes, 0, sizeof(planes));
            buffer.index = i;
            buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
            buffer.memory = V4L2_MEMORY_MMAP;
            buffer.m.planes = planes;
            buffer.length = outputPlaneCount;
            ioctlRet = SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_QUERYBUF, &buffer);
            ASSERT(ioctlRet != -1);

            rawOutputFrames[i].width = format.fmt.pix_mp.width;
            rawOutputFrames[i].height = format.fmt.pix_mp.height;
            rawOutputFrames[i].fourcc = format.fmt.pix_mp.pixelformat;

            for (int j=0; j<outputPlaneCount; j++) {
                // length and mem_offset are filled by VIDIOC_QUERYBUF above
                void* address = SIMULATE_V4L2_OP(Mmap)(NULL,
                                              buffer.m.planes[j].length,
                                              PROT_READ | PROT_WRITE,
                                              MAP_SHARED, fd,
                                              buffer.m.planes[j].m.mem_offset);
                ASSERT(address);
                if (j == 0) {
                    rawOutputFrames[i].data = static_cast<uint8_t*>(address);
                    rawOutputFrames[i].offset[0] = 0;
                } else {
                    rawOutputFrames[i].offset[j] = static_cast<uint8_t*>(address) - rawOutputFrames[i].data;
                }

                rawOutputFrames[i].pitch[j] = format.fmt.pix_mp.plane_fmt[j].bytesperline;
            }
        }
    } else if (IS_DMA_BUF() || IS_DRM_NAME()) {
        // setup all textures and eglImages
        eglImages.resize(outputQueueCapacity);
        textureIds.resize(outputQueueCapacity);

        if (!eglContext)
            eglContext = eglInit(x11Display, x11Window, 0 /*VA_FOURCC_RGBA*/, IS_DMA_BUF());

        glGenTextures(outputQueueCapacity, &textureIds[0] );
        for (i=0; i<outputQueueCapacity; i++) {
             int ret = 0;
             ret = SIMULATE_V4L2_OP(UseEglImage)(fd, eglContext->eglContext.display, eglContext->eglContext.context, i, &eglImages[i]);
             ASSERT(ret == 0);

             GLenum target = GL_TEXTURE_2D;
             if (IS_DMA_BUF())
                 target = GL_TEXTURE_EXTERNAL_OES;
             glBindTexture(target, textureIds[i]);
             imageTargetTexture2D(target, eglImages[i]);

             glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
             glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
             DEBUG("textureIds[%d]: 0x%x, eglImages[%d]: 0x%p", i, textureIds[i], i, eglImages[i]);
        }
    }
#endif

#ifndef ANDROID
    // feed output frames first
    for (i=0; i<outputQueueCapacity; i++) {
        if (!takeOneOutputFrame(fd, i)) {
            ASSERT(0);
        }
    }
#else
    struct v4l2_buffer buffer;

    err = native_window_set_buffer_count(mNativeWindow.get(), outputQueueCapacity);
    if (err != 0) {
        fprintf(stderr, "native_window_set_buffer_count failed: %s (%d)", strerror(-err), -err);
        return -1;
    }

    //queue buffs
    for (uint32_t i = 0; i < outputQueueCapacity; i++) {
        ANativeWindowBuffer* pbuf = NULL;
        memset(&buffer, 0, sizeof(buffer));

        err = native_window_dequeue_buffer_and_wait(mNativeWindow.get(), &pbuf);
        if (err != 0) {
            fprintf(stderr, "dequeueBuffer failed: %s (%d)\n", strerror(-err), -err);
            return -1;
        }

        buffer.m.userptr = (unsigned long)pbuf;
        buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
        buffer.index = i;

        ioctlRet = SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_QBUF, &buffer);
        ASSERT(ioctlRet != -1);
        mWindBuff.push_back(pbuf);
    }

    for (uint32_t i = 0; i < minUndequeuedBuffs; i++) {
        memset(&buffer, 0, sizeof(buffer));
        buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;

        ioctlRet = SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_DQBUF, &buffer);
        ASSERT(ioctlRet != -1);

        err = mNativeWindow->cancelBuffer(mNativeWindow.get(), mWindBuff[buffer.index], -1);
        if (err) {
            fprintf(stderr, "queue empty window buffer error\n");
            return -1;
        }
    }
#endif

    // output port starts as late as possible to adopt user provide output buffer
    type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    ioctlRet = SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_STREAMON, &type);
    ASSERT(ioctlRet != -1);

    bool event_pending=true; // try to get video resolution.
    int dqCountAfterEOS = 0;
    do {
        if (event_pending) {
            handleResolutionChange(fd);
        }

        takeOneOutputFrame(fd);
        if (!feedOneInputFrame(input, fd)) {
            if (stagingBufferInDevice == 0)
                break;
            dqCountAfterEOS++;
        }
        if (dqCountAfterEOS == inputQueueCapacity)  // input drain
            break;
    } while (SIMULATE_V4L2_OP(Poll)(fd, true, &event_pending) == 0);

    // drain output buffer
    int retry = 3;
    while (takeOneOutputFrame(fd) || (--retry)>0) { // output drain
        usleep(10000);
    }

    calcFps.fps(renderFrameCount);
    // SIMULATE_V4L2_OP(Munmap)(void* addr, size_t length)
    possibleWait(input->getMimeType());

    // release queued input/output buffer
    memset(&reqbufs, 0, sizeof(reqbufs));
    reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
    reqbufs.memory = V4L2_MEMORY_MMAP;
    reqbufs.count = 0;
    ioctlRet = SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_REQBUFS, &reqbufs);
    ASSERT(ioctlRet != -1);

    memset(&reqbufs, 0, sizeof(reqbufs));
    reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    reqbufs.memory = V4L2_MEMORY_MMAP;
    reqbufs.count = 0;
    ioctlRet = SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_REQBUFS, &reqbufs);
    ASSERT(ioctlRet != -1);

    // stop input port
    type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
    ioctlRet = SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_STREAMOFF, &type);
    ASSERT(ioctlRet != -1);

    // stop output port
    type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    ioctlRet = SIMULATE_V4L2_OP(Ioctl)(fd, VIDIOC_STREAMOFF, &type);
    ASSERT(ioctlRet != -1);

#ifndef ANDROID
    if(textureIds.size())
        glDeleteTextures(textureIds.size(), &textureIds[0]);
    ASSERT(glGetError() == GL_NO_ERROR);
#endif

#ifdef ANDROID
    //TODO, some resources need to destroy?
#elif __ENABLE_V4L2_GLX__
    glxRelease(glxContext, &pixmaps[0], &glxPixmaps[0], pixmaps.size());
#else
    for (i=0; i<eglImages.size(); i++) {
        destroyImage(eglContext->eglContext.display, eglImages[i]);
    }
    /*
    there is still randomly fail in mesa; no good idea for it. seems mesa bug
    0  0x00007ffff079c343 in _mesa_symbol_table_dtor () from /usr/lib/x86_64-linux-gnu/libdricore9.2.1.so.1
    1  0x00007ffff073c55d in glsl_symbol_table::~glsl_symbol_table() () from /usr/lib/x86_64-linux-gnu/libdricore9.2.1.so.1
    2  0x00007ffff072a4d5 in ?? () from /usr/lib/x86_64-linux-gnu/libdricore9.2.1.so.1
    3  0x00007ffff072a4bd in ?? () from /usr/lib/x86_64-linux-gnu/libdricore9.2.1.so.1
    4  0x00007ffff064b48f in _mesa_reference_shader () from /usr/lib/x86_64-linux-gnu/libdricore9.2.1.so.1
    5  0x00007ffff0649397 in ?? () from /usr/lib/x86_64-linux-gnu/libdricore9.2.1.so.1
    6  0x000000000040624d in releaseShader (program=0x77cd90) at ./egl/gles2_help.c:158
    7  eglRelease (context=0x615920) at ./egl/gles2_help.c:310
    8  0x0000000000402ca8 in main (argc=<optimized out>, argv=<optimized out>) at v4l2decode.cpp:531
    */
    if (eglContext)
        eglRelease(eglContext);
#endif

    // close device
    ioctlRet = SIMULATE_V4L2_OP(Close)(fd);
    ASSERT(ioctlRet != -1);

    if(input)
        delete input;

    if (outfp)
        fclose(outfp);

    if (dumpOutputName)
        free(dumpOutputName);

#if __ENABLE_V4L2_GLX__
    if (x11Display && x11Window)
        XDestroyWindow(x11Display, x11Window);
    if (x11Display)
        XCloseDisplay(x11Display);
#endif

    fprintf(stdout, "decode done\n");
}
Beispiel #13
0
int showStatement(const unsigned int statement_id)
{
	// Frame control
	int ticks_then = -1;
	int ticks_now;
	unsigned int target_fps = 60;
	int delay = 1000 / target_fps;
	enum state_machine { fade_in, fade_off, fade_out };
	enum state_machine state = fade_in;
	
	// Variables
	Uint8 fade = 0;
	int shade = 0;
		
	// Rendering variables
	SDL_Event event_handler;
	int terminate = 0;
	
	// SDL variables
	SDL_Surface *display;
	display = SDL_GetVideoSurface();
	SDL_Surface *image;
	
	// Load image
	char image_filename[255];
	sprintf(image_filename, "../Resources/statement%u.png", statement_id);
	image = loadImage(image_filename);

	// Rendering loop
	while (!terminate) {
		// Handle events
		while (SDL_PollEvent(&event_handler) ) {
			switch (event_handler.type) {
				case SDL_KEYDOWN:
				case SDL_QUIT:
					state = fade_out;
					break;
			}
		}
		
		// Blitting
		SDL_FillRect(display, NULL, SDL_MapRGB(display->format, 0, 0, 0) );
		SDL_SetAlpha(image, SDL_RLEACCEL | SDL_SRCALPHA, fade);
		SDL_BlitSurface(image, NULL, display, NULL);
		
		// State machine TODO
		switch (state) {
			case fade_in:
				shade += 8;
				if (shade >= 255) {
					state = fade_off;
					fade = 255;
				} else {
					fade = shade;
				}
				break;
				
			case fade_out:
				shade -= 8;
				if (shade <= 0) {
					fade = 0;
					terminate = 1;
				} else {
					fade = shade;
				}
				break;
				
			default:
				shade = 255;
				break;
		}
		
		// Flip
		SDL_Flip(display);
		SDL_Delay(delay);
		
		// Constant FPS implementation
		if (ticks_then > 0) {
			ticks_now = SDL_GetTicks();
			delay += (1000 / target_fps - (ticks_now - ticks_then) );
			ticks_then = ticks_now;
			
			if (delay < 0) delay = 1000 / target_fps; // reset delay
		} else {
			ticks_then = SDL_GetTicks();
		}
	} // rendering loop
	
	// Clean-up
	destroyImage(image);
	
	return 0;
}
Beispiel #14
0
int stop_ObstacleDetector()
{
 destroyImage(mask);
 return 1;
}
Beispiel #15
0
static int doResize(OMX_RESIZER *resizer, IMAGE *inImage, IMAGE *outImage){
	int retVal= OMX_IMAGE_OK;
	OMX_BUFFERHEADERTYPE *pBufHeader = resizer->pInputBufferHeader;
	pBufHeader->nFilledLen=inImage->nData;
	pBufHeader->nFlags = OMX_BUFFERFLAG_EOS;
	
	int ret = OMX_EmptyThisBuffer(resizer->handle, pBufHeader);
	if (ret != OMX_ErrorNone) {
		 retVal |= OMX_IMAGE_ERROR_MEMORY;
	}
	
	if(ilclient_wait_for_event(resizer->component,OMX_EventPortSettingsChanged,resizer->outPort, 
			0, 0, 1, ILCLIENT_EVENT_ERROR | ILCLIENT_PARAMETER_CHANGED, TIMEOUT_MS) == 0){	
		
		destroyImage(inImage);
		retVal|= resizePortSettingsChanged(resizer, outImage);
		if(retVal == OMX_IMAGE_OK){
			if (OMX_FillThisBuffer(resizer->handle, 
				resizer->pOutputBufferHeader) != OMX_ErrorNone) {
				retVal|=OMX_IMAGE_ERROR_MEMORY;
			}
		}		
	}
	
	if(ilclient_wait_for_event(resizer->component, OMX_EventBufferFlag, resizer->outPort, 
				0, OMX_BUFFERFLAG_EOS, 0, ILCLIENT_BUFFER_FLAG_EOS, TIMEOUT_MS) != 0){
		
		retVal|= OMX_IMAGE_ERROR_NO_EOS;
	}
	
	ret= OMX_FreeBuffer(resizer->handle, resizer->inPort, resizer->pInputBufferHeader);
	if(ret!= OMX_ErrorNone){
		retVal|=OMX_IMAGE_ERROR_MEMORY;
	}
	
	ret = OMX_SendCommand(resizer->handle, OMX_CommandPortDisable, resizer->inPort, NULL);
	if(ret!= OMX_ErrorNone){
		retVal |= OMX_IMAGE_ERROR_PORTS;
	}
		
	ilclient_wait_for_event(resizer->component, OMX_EventCmdComplete, 
			OMX_CommandPortDisable, 0, resizer->inPort, 0, 
			ILCLIENT_PORT_DISABLED, TIMEOUT_MS);		
	
	OMX_SendCommand(resizer->handle, OMX_CommandFlush, resizer->outPort, NULL);
		
	ilclient_wait_for_event(resizer->component,OMX_EventCmdComplete, OMX_CommandFlush, 
		0, resizer->outPort, 0, ILCLIENT_PORT_FLUSH ,TIMEOUT_MS);	
			
	ret= OMX_FreeBuffer(resizer->handle, resizer->outPort, resizer->pOutputBufferHeader);	
	if(ret!= OMX_ErrorNone){
		retVal|=OMX_IMAGE_ERROR_MEMORY;
	}
	
	ret= OMX_SendCommand(resizer->handle, OMX_CommandPortDisable, resizer->outPort, NULL);	
	if(ret!= OMX_ErrorNone){
		retVal|=OMX_IMAGE_ERROR_PORTS;
	}
	
	ilclient_change_component_state(resizer->component, OMX_StateIdle);
	ilclient_change_component_state(resizer->component, OMX_StateLoaded);
	
	return retVal;
}
Beispiel #16
0
int blitPreviews(experiment *experiments, unsigned int runs)
{
	// Viewport variables
	const unsigned int viewport_w = 340;
	const unsigned int viewport_h = 255;
	const float sequence_length = 58.0f + (2.0f / 11.0f);
	
	// Viewport data
	typedef struct viewport_data_t {
		SDL_Rect viewport;
		unsigned int tile;
		unsigned int tiles;
		unsigned int seg;
		float cumulative_error;
		float tile_error;
		unsigned int field;
		unsigned int base_fields;
		unsigned int cur_fields;
	} viewport_data;
	
	viewport_data *viewports;
	viewports = malloc(runs * sizeof(viewport_data) );
	
	if (!viewports) {
		fprintf(stderr, "Error allocating memory for viewport data.\n");
		return 1;
	}
	
	if (runs > 6) {
		fprintf(stderr, "Non-fatal: Cannot display more than six runs! Truncating output to six screens.\n");
		runs = 5; // starting from zero
	}
	
	for (int i = 0; i < runs; i++) {
		// Viewport dimensions
		viewports[i].viewport.w = viewport_w;
		viewports[i].viewport.h = viewport_h;
		
		switch (i) {
			case 0:
				viewports[i].viewport.x = 1;
				viewports[i].viewport.y = 1;
				break;
			case 1:
				viewports[i].viewport.x = 342;
				viewports[i].viewport.y = 1;
				break;
			case 2:
				viewports[i].viewport.x = 683;
				viewports[i].viewport.y = 1;
				break;
			case 3:
				viewports[i].viewport.x = 1;
				viewports[i].viewport.y = 512;
				break;
			case 4:
				viewports[i].viewport.x = 342;
				viewports[i].viewport.y = 512;
				break;
			case 5:
				viewports[i].viewport.x = 683;
				viewports[i].viewport.y = 512;
				break;
		}
		
		// Viewport tiles and scaling
		viewports[i].tile = 0; // start at the beginning
		viewports[i].tiles = experiments[i].seg * experiments[i].seg * 15;
		viewports[i].seg = experiments[i].seg;
		
		// Viewport tile jitter
		viewports[i].cumulative_error = 0.0f;
		viewports[i].tile_error = fmod((60.0f * sequence_length) / viewports[i].tiles, 1.0f);
		viewports[i].field = 0; // beginning again
		viewports[i].base_fields = (unsigned int) lrint(floor( ((60.0f * sequence_length) / viewports[i].tiles) ) );
		viewports[i].cur_fields = viewports[i].base_fields;
	}
	
	// Display variables
	SDL_Surface *display;
	display = SDL_GetVideoSurface();
	const SDL_Rect preview_size = { 0, 0, viewport_w, viewport_h };
	const int target_fps = 60;
	SDL_Event event_handler;
	int terminate = 0;
	int ticks_then = -1;
	int ticks_now = 0;
	int field = 0;
	int delay = 1000 / target_fps;
	
	// Create previews
	SDL_Thread *create_previews;
	int create_previews_return;
	float progress = 0;
	create_previews_args create_previews_arg = { experiments, runs, preview_size, &progress };
	create_previews = SDL_CreateThread((int (*)(void *))createPreviews, &create_previews_arg);
	
	if (create_previews == NULL) {
		fprintf(stderr, "SDL: Unable to create preview tile creation thread: %s\n", SDL_GetError() );
		return 1;
	}
	
	displayCountdownScreen(&progress);
	
	SDL_WaitThread(create_previews, &create_previews_return);
	
	if (create_previews_return != 0) {
		fprintf(stderr, "SDL: Preview tile creation thread failed.\n");
		return 1;
	}
	
	// Questions display
	const char *question_1_image_filename = "../Resources/question1.png";
	const char *question_2_image_filename = "../Resources/question2.png";
	SDL_Surface *question_1_image, *question_2_image;
	question_1_image = loadImage(question_1_image_filename);
	question_2_image = loadImage(question_2_image_filename);
	SDL_Rect question_image_location;
	question_image_location.w = 1022;
	question_image_location.h = 254;
	question_image_location.x = 1;
	question_image_location.y = 257;
	int question_image_fade = 0;
	const Uint8 question_image_fade_increment = 8;
	enum question_state_machine {
		q1_fadein,
		q1_static,
		q1_fadeout,
		q2_fadein,
		q2_static,
		q2_fadeout
	} question_state = q1_fadein;
	int question_keypress = 0;
	
	
	// Display routine
	while (!terminate) {
		// Handle events
		while (SDL_PollEvent(&event_handler) ) {
			switch (event_handler.type) {
				case SDL_KEYDOWN:
					question_keypress = 1;
					break;
				case SDL_QUIT:
					// should probably clean-up...
					exit(0);
					break;
				default:
					break;
			} // switch event_handler
		} // while SDL_PollEvent
		
		// State machine
		switch (question_state) {
			case q1_fadein:
				question_image_fade += question_image_fade_increment;
				if (question_image_fade >= 255) {
					question_image_fade = 255;
					question_state = q1_static;
				}
				break;
				
			case q1_static:
				if (question_keypress) {
					question_keypress = 0;
					question_state = q1_fadeout;
				}
				break;
			
			case q1_fadeout:
				question_image_fade -= question_image_fade_increment;
				if (question_image_fade <= 0) {
					question_image_fade = 0;
					question_state = q2_fadein;
				}
				break;
				
			case q2_fadein:
				question_image_fade += question_image_fade_increment;
				if (question_image_fade >= 255) {
					question_image_fade = 255;
					question_state = q2_static;
				}
				break;
				
			case q2_static:
				if (question_keypress) {
					question_keypress = 0;
					question_state = q2_fadeout;
				}
				break;
				
			case q2_fadeout:
				question_image_fade -= question_image_fade_increment;
				if (question_image_fade <= 0) {
					question_image_fade = 0;
					terminate = 1;
				}
				break;
				
			default:
				printf("Invalid state for blitPreviews.\n");
				break;
		} // switch question_state
		
		// Calculations
		for (int i = 0; i < runs; i++) {
			// Field updating
			viewports[i].field++;
			
			if (viewports[i].field == viewports[i].cur_fields) {
				// Reset tile
				viewports[i].field = 0;
				viewports[i].tile++;
				
				// Check we haven't gone beyond our bounds
				if (viewports[i].tile == viewports[i].tiles) {
					viewports[i].tile = 0;
				}
				
				// Calculate tile display duration
				viewports[i].cumulative_error += viewports[i].tile_error;
				if (viewports[i].cumulative_error >= 1.0f) {
					// Standard duration frame
					viewports[i].cur_fields = viewports[i].base_fields;
					viewports[i].cumulative_error -= 1.0f;
				} else {
					// Extended duration frame
					viewports[i].cur_fields = viewports[i].base_fields + 1;
				}
			}
		}
		
		// Rendering
		SDL_FillRect(display, NULL, SDL_MapRGB(display->format, 0, 0, 0) ); // clear with black
		for (int i = 0; i < runs; i++) {
			SDL_BlitSurface(previews[i][viewports[i].tile], NULL, display, &viewports[i].viewport);
		}
		
		// Question display
		switch (question_state) {
			case q1_fadein:
			case q1_static:
			case q1_fadeout:
				SDL_SetAlpha(question_1_image, SDL_RLEACCEL | SDL_SRCALPHA, question_image_fade);
				SDL_BlitSurface(question_1_image, NULL, display, &question_image_location);
				break;
				
			case q2_fadein:
			case q2_static:
			case q2_fadeout:
				SDL_SetAlpha(question_2_image, SDL_RLEACCEL | SDL_SRCALPHA, question_image_fade);
				SDL_BlitSurface(question_2_image, NULL, display, &question_image_location);
				break;
		} // switch question_state
	
		// Flipping
		SDL_Flip(display);
	
		// Delay calculation
		if (ticks_then > 0) {
			ticks_now = SDL_GetTicks();
			delay += (1000 / target_fps - (ticks_now - ticks_then) ); // adjust delay
			ticks_then = ticks_now;
			
			if (delay < 0) delay = 1000 / target_fps; // reset delay
		} else {
			ticks_then = SDL_GetTicks();
		}
		
		field++;
		
		SDL_Delay(delay);
	} // while !terminate
	
	// Clean-up
	destroyImage(question_1_image);
	destroyImage(question_2_image);
	free(viewports);
	
	return 0;
}
void ShapesLoader::drawImageFromShape
(	Shape *	shape,
	uint	index,
	char	detail,		//= '\0'
	uint	sindex		//= -1
){	char	filename[256];
	uint	i;
	uint	y;
	uint	x;
	uint	width		= shape->_width * 8;
	uint	height		= shape->_nData / shape->_width * 8;

	::stage++; uchar * * image = createImage(width, height);

	::stage++;
	if(sindex == -1)
		sprintf
		(	filename,
			"rai/Analyser/TestShapesLoader/%ld.pgm",
			index
		);
	else
		sprintf
		(	filename,
			"rai/Analyser/TestShapesLoader/%ld%c%ld.pgm",
			index,
			detail,
			sindex
		);

	for(i = 0; i < shape->_nData; i++)
		for(y = 0; y < 8; y++)
		for(x = 0; x < 8; x++)
			image[y + (i / shape->_width) * 8][x + (i % shape->_width) * 8] = shape->_data[i] * 127 + 64;

	for(i = 0; i < shape->_nZones; i++)
	{
		
		Zone const * const zone = shape->_zones[i];
		float a;

		for(a = 0; a < Math::PI() * 2; a += 0.05f)
		{	x = (int)(zone->_x * 8 + cos(a) * zone->_exitRadius * 8);
			y = (int)(zone->_y * 8 + sin(a) * zone->_exitRadius * 8);
			if(x >= 0 && y >= 0 && x < width && y < height)
				image[y][x] = 0;
		}

		for(a = 0; a < 1.0f; a += 0.01f)
		{	x = (int)(zone->_x * 8 + cos(zone->_exitAngle + zone->_exitArc) * zone->_exitRadius * 8 * a);
			y = (int)(zone->_y * 8 + sin(zone->_exitAngle + zone->_exitArc) * zone->_exitRadius * 8 * a);
			if(x >= 0 && y >= 0 && x < width && y < height)
				image[y][x] = 0;
			x = (int)(zone->_x * 8 + cos(zone->_exitAngle - zone->_exitArc) * zone->_exitRadius * 8 * a);
			y = (int)(zone->_y * 8 + sin(zone->_exitAngle - zone->_exitArc) * zone->_exitRadius * 8 * a);
			if(x >= 0 && y >= 0 && x < width && y < height)
				image[y][x] = 0;
		}

		for(a = 0; a < Math::PI() * 2; a += 0.05f)
		{	x = (int)(zone->_x * 8 + cos(a) * zone->_enterRadius * 8);
			y = (int)(zone->_y * 8 + sin(a) * zone->_enterRadius * 8);
			if(x >= 0 && y >= 0 && x < width && y < height)
				image[y][x] = 255;
		}

		for(a = 0; a < 1.0f; a += 0.01f)
		{	x = (int)(zone->_x * 8 + cos(zone->_enterAngle + zone->_enterArc) * zone->_enterRadius * 8 * a);
			y = (int)(zone->_y * 8 + sin(zone->_enterAngle + zone->_enterArc) * zone->_enterRadius * 8 * a);
			if(x >= 0 && y >= 0 && x < width && y < height)
				image[y][x] = 255;
			x = (int)(zone->_x * 8 + cos(zone->_enterAngle - zone->_enterArc) * zone->_enterRadius * 8 * a);
			y = (int)(zone->_y * 8 + sin(zone->_enterAngle - zone->_enterArc) * zone->_enterRadius * 8 * a);
			if(x >= 0 && y >= 0 && x < width && y < height)
				image[y][x] = 255;
		}

		for(x = -1; x < i; x++)
			image[(int)(zone->_y * 8)][(int)(zone->_x * 8) + x] = 255;

	}

	::stage++; writeImage(filename, image, width, height);

	::stage++; destroyImage(image);

}
Beispiel #18
0
void destroyScene(Scene* scene){
    free(scene->triangles);
    free(scene->lights);
    destroyImage(&scene->image);
    free(scene->materials);
}
  /*
   * shows an lti::mathObject
   * @param data the object to be shown.
   */
  bool fastViewer::show(const image& img) {
    // Draw screen onto display

    if (img.rows()>0 && img.columns()>0) {
      if (data.size() == img.size()) {
        data.fill(img);
      } else {
        destroyImage();
        createImage(img);
      }
    } else {
      setStatusString("empty image");
      return false;
    }

    if (useShareMemory) {
      XShmPutImage(display_info.display,
                   display_info.win,
                   display_info.gc,
                   display_info.shmimage,
                   0, 0, 0, 0,
                   display_info.width,
                   display_info.height, false);
    } else {
      XPutImage(display_info.display,
                display_info.win,
                display_info.gc,
                display_info.shmimage,
                0, 0, 0, 0,
                display_info.width,
                display_info.height);
    }

    XSync(display_info.display,0);

    return true;
  }