Beispiel #1
0
int gpuvm_init(unsigned ndevs, void **devs, int flags) {
	// check arguments
	if(ndevs == 0) {
		fprintf(stderr, "gpuvm_init: zero devices not allowed\n");
		return GPUVM_EARG;
	}
	if(flags & ~(GPUVM_API | GPUVM_STAT | GPUVM_WRITER_SIG_BLOCK | 
							 GPUVM_UNLINK_NO_SYNC_BACK) || !(flags & GPUVM_API)) {
		fprintf(stderr, "gpuvm_init: invalid flags\n");
		return GPUVM_EARG;
	}

	// check state
	if(ndevs_g) {
		fprintf(stderr, "gpuvm_init: GPUVM already initialized\n");
		return GPUVM_ETWICE;
	}
	ndevs_g = ndevs;

	// initialize auxiliary structures
	int err = 0;
	err = salloc_init();
	if(err)
		return err;

	// initialize devices
	devs_g = (void**)smalloc(ndevs * sizeof(void*));
	if(!devs_g)
		return GPUVM_ESALLOC;

	if(flags & GPUVM_OPENCL) {
		if(!devs) {
			fprintf(stderr, "gpuvm_init: null pointer to devices not allowed\n");
			return GPUVM_ENULL;
		}
		memcpy(devs_g, devs, ndevs * sizeof(void*));
	} else if(flags & GPUVM_CUDA) {
		// ignore devs, just zero out devs_g
		memset(devs_g, 0, ndevs * sizeof(void*));
	}

	// continue with initialization
	(err = sync_init()) || 
		(err = devapi_init(flags)) ||
		(err = handler_init()) || 
		(err = stat_init(flags)) || 
		(err = tsem_init()) || 
		(err = wthreads_init());
	if(err)
		return err;
	
	return 0;
}  // gpuvm_init
/*
 * Create a threadpool, initialize variables, etc
 *
 */
struct tpool *pool_create(int queue_size, int num_threads)
{
	struct tpool *pool;
	int i;
	
	// use the default value at first
	if(queue_size <= 0)
		queue_size = STANDBY_SIZE;
	if(num_threads <= 0)
		num_threads = MAX_THREADS;

	// allocate memory for thread pool data structure
	pool = (struct tpool*)malloc(sizeof(struct tpool) + sizeof(pthread_t) * num_threads);
	if(!pool)
		goto done;
	memset(pool, 0, sizeof(struct tpool) + sizeof(pthread_t) * num_threads);
	pool->thread_count = num_threads;
	//pool->queue_count = queue_size;
	pool->quit = 0;

	// initialize the locks
	tsem_init(&pool->sem, 0);
	pthread_mutex_init(&pool->queue_mutex, NULL);

	// initialize the task queue
	for(i = 0; i < PRIORITY_LEVEL; i++) {
		pool->task_queue[i].prev = pool->task_queue[i].next = &(pool->task_queue[i]);
	}

	//initialize all the threads
	for(i = 0; i < num_threads; i++) {
		pthread_create(&pool->tid[i], NULL, thread_do_work, (void*)pool);
	}

done:
    return pool;
}
/** The Constructor 
 */
OMX_ERRORTYPE omx_videosrc_component_Constructor(OMX_COMPONENTTYPE *openmaxStandComp,OMX_STRING cComponentName) {
 
  OMX_ERRORTYPE err = OMX_ErrorNone;  
  omx_base_video_PortType *pPort;
  omx_videosrc_component_PrivateType* omx_videosrc_component_Private;
  OMX_U32 i;

  DEBUG(DEB_LEV_FUNCTION_NAME,"In %s \n",__func__);

  if (!openmaxStandComp->pComponentPrivate) {
    openmaxStandComp->pComponentPrivate = calloc(1, sizeof(omx_videosrc_component_PrivateType));
    if(openmaxStandComp->pComponentPrivate == NULL) {
      return OMX_ErrorInsufficientResources;
    }
  }

  omx_videosrc_component_Private = openmaxStandComp->pComponentPrivate;
  omx_videosrc_component_Private->ports = NULL;
  omx_videosrc_component_Private->deviceHandle = -1;
  
  err = omx_base_source_Constructor(openmaxStandComp, cComponentName);
  
  omx_videosrc_component_Private->sPortTypesParam[OMX_PortDomainVideo].nStartPortNumber = 0;
  omx_videosrc_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts = 1;

    /** Allocate Ports and call port constructor. */  
  if (omx_videosrc_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts && !omx_videosrc_component_Private->ports) {
    omx_videosrc_component_Private->ports = calloc(omx_videosrc_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts, sizeof(omx_base_PortType *));
    if (!omx_videosrc_component_Private->ports) {
      return OMX_ErrorInsufficientResources;
    }
    for (i=0; i < omx_videosrc_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts; i++) {
      omx_videosrc_component_Private->ports[i] = calloc(1, sizeof(omx_base_video_PortType));
      if (!omx_videosrc_component_Private->ports[i]) {
        return OMX_ErrorInsufficientResources;
      }
    }
  }

  base_video_port_Constructor(openmaxStandComp, &omx_videosrc_component_Private->ports[0], 0, OMX_FALSE);
  omx_videosrc_component_Private->ports[0]->Port_AllocateBuffer = videosrc_port_AllocateBuffer;
  omx_videosrc_component_Private->ports[0]->Port_FreeBuffer = videosrc_port_FreeBuffer;
  omx_videosrc_component_Private->ports[0]->Port_AllocateTunnelBuffer = videosrc_port_AllocateTunnelBuffer;
  omx_videosrc_component_Private->ports[0]->Port_FreeTunnelBuffer = videosrc_port_FreeTunnelBuffer;

  pPort = (omx_base_video_PortType *) omx_videosrc_component_Private->ports[OMX_BASE_SOURCE_OUTPUTPORT_INDEX];
  
  pPort->sPortParam.format.video.nFrameWidth = 320;
  pPort->sPortParam.format.video.nFrameHeight= 240;
  pPort->sPortParam.format.video.eColorFormat= OMX_COLOR_FormatYUV420Planar;
  pPort->sVideoParam.eColorFormat = OMX_COLOR_FormatYUV420Planar;

  pPort->sPortParam.nBufferSize = pPort->sPortParam.format.video.nFrameWidth*
                                  pPort->sPortParam.format.video.nFrameHeight*3; // RGB888
  omx_videosrc_component_Private->iFrameSize = pPort->sPortParam.nBufferSize;

  omx_videosrc_component_Private->BufferMgmtCallback = omx_videosrc_component_BufferMgmtCallback;
  omx_videosrc_component_Private->destructor = omx_videosrc_component_Destructor;
  omx_videosrc_component_Private->messageHandler = omx_videosrc_component_MessageHandler;

  noViderSrcInstance++;
  if(noViderSrcInstance > MAX_COMPONENT_VIDEOSRC) {
    return OMX_ErrorInsufficientResources;
  }

  openmaxStandComp->SetParameter  = omx_videosrc_component_SetParameter;
  openmaxStandComp->GetParameter  = omx_videosrc_component_GetParameter;

  /* Write in the default paramenters */
  omx_videosrc_component_Private->videoReady = OMX_FALSE;
  if(!omx_videosrc_component_Private->videoSyncSem) {
    omx_videosrc_component_Private->videoSyncSem = calloc(1,sizeof(tsem_t));
    if(omx_videosrc_component_Private->videoSyncSem == NULL) return OMX_ErrorInsufficientResources;
    tsem_init(omx_videosrc_component_Private->videoSyncSem, 0);
  }

  omx_videosrc_component_Private->bOutBufferMemoryMapped = OMX_FALSE;

  /* Test if Camera Attached */
  omx_videosrc_component_Private->deviceHandle = open(VIDEO_DEV_NAME, O_RDWR /* required */  | O_NONBLOCK, 0);
  if (omx_videosrc_component_Private->deviceHandle < 0) {
    DEBUG(DEB_LEV_ERR, "In %s Unable to open video capture device %s! errno=%d  ENODEV : %d \n", 
      __func__,VIDEO_DEV_NAME,errno,ENODEV);
    return OMX_ErrorHardware;
  } 

  omx_videosrc_component_Private->pixel_format = V4L2_PIX_FMT_YUV420;

  err = init_device(omx_videosrc_component_Private);

  err = init_mmap(omx_videosrc_component_Private);

  return err;
}
/** The Constructor
 *
 * @param openmaxStandComp is the handle to be constructed
 * @param cComponentName is the name of the constructed component
 *
 */
OMX_ERRORTYPE omx_xvideo_sink_component_Constructor(OMX_COMPONENTTYPE *openmaxStandComp,OMX_STRING cComponentName) {
  OMX_ERRORTYPE err = OMX_ErrorNone;
  omx_xvideo_sink_component_PortType *pPort;
  omx_xvideo_sink_component_PrivateType* omx_xvideo_sink_component_Private;

  if (!openmaxStandComp->pComponentPrivate) {
    DEBUG(DEB_LEV_FUNCTION_NAME, "In %s, allocating component\n", __func__);
    openmaxStandComp->pComponentPrivate = calloc(1, sizeof(omx_xvideo_sink_component_PrivateType));
    if(openmaxStandComp->pComponentPrivate == NULL) {
      return OMX_ErrorInsufficientResources;
    }
  } else {
    DEBUG(DEB_LEV_FUNCTION_NAME, "In %s, Error Component %x Already Allocated\n", __func__, (int)openmaxStandComp->pComponentPrivate);
  }

  omx_xvideo_sink_component_Private = openmaxStandComp->pComponentPrivate;
  omx_xvideo_sink_component_Private->ports = NULL;

  /** we could create our own port structures here
    * fixme maybe the base class could use a "port factory" function pointer?
    */
  err = omx_base_sink_Constructor(openmaxStandComp, cComponentName);

  omx_xvideo_sink_component_Private->sPortTypesParam[OMX_PortDomainVideo].nStartPortNumber = 0;
  omx_xvideo_sink_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts = 1;

  /** Allocate Ports and call port constructor. */
  if ((omx_xvideo_sink_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts )  && !omx_xvideo_sink_component_Private->ports) {
    omx_xvideo_sink_component_Private->ports = calloc((omx_xvideo_sink_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts ), sizeof(omx_base_PortType *));
    if (!omx_xvideo_sink_component_Private->ports) {
      return OMX_ErrorInsufficientResources;
    }
    omx_xvideo_sink_component_Private->ports[0] = calloc(1, sizeof(omx_xvideo_sink_component_PortType));
    if (!omx_xvideo_sink_component_Private->ports[0]) {
      return OMX_ErrorInsufficientResources;
    }
    base_video_port_Constructor(openmaxStandComp, &omx_xvideo_sink_component_Private->ports[0], 0, OMX_TRUE);
  }

  pPort = (omx_xvideo_sink_component_PortType *) omx_xvideo_sink_component_Private->ports[OMX_BASE_SINK_INPUTPORT_INDEX];

  /** Domain specific section for the allocated port. */

  pPort->sPortParam.format.video.nFrameWidth = 352;
  pPort->sPortParam.format.video.nFrameHeight = 288;
  pPort->sPortParam.format.video.nBitrate = 0;
  pPort->sPortParam.format.video.xFramerate = 25;
  pPort->sPortParam.format.video.eColorFormat = OMX_COLOR_FormatYUV420Planar;

  //  Figure out stride, slice height, min buffer size

  pPort->sPortParam.format.video.nStride = calcStride(pPort->sPortParam.format.video.nFrameWidth, pPort->sPortParam.format.video.eColorFormat);
  pPort->sPortParam.format.video.nSliceHeight = pPort->sPortParam.format.video.nFrameHeight;  //  No support for slices yet
  pPort->sPortParam.nBufferSize = (OMX_U32) abs(pPort->sPortParam.format.video.nStride) * pPort->sPortParam.format.video.nSliceHeight;

  pPort->sVideoParam.eColorFormat = OMX_COLOR_FormatYUV420Planar;
  pPort->sVideoParam.xFramerate = 25;

  DEBUG(DEB_LEV_PARAMS, "In %s, bSize=%d stride=%d\n", __func__,(int)pPort->sPortParam.nBufferSize,(int)pPort->sPortParam.format.video.nStride);

  /** Set configs */
  setHeader(&pPort->omxConfigCrop, sizeof(OMX_CONFIG_RECTTYPE));
  pPort->omxConfigCrop.nPortIndex = OMX_BASE_SINK_INPUTPORT_INDEX;
  pPort->omxConfigCrop.nLeft = pPort->omxConfigCrop.nTop = 0;
  pPort->omxConfigCrop.nWidth = pPort->omxConfigCrop.nHeight = 0;

  setHeader(&pPort->omxConfigRotate, sizeof(OMX_CONFIG_ROTATIONTYPE));
  pPort->omxConfigRotate.nPortIndex = OMX_BASE_SINK_INPUTPORT_INDEX;
  pPort->omxConfigRotate.nRotation = 0;  //Default: No rotation (0 degrees)

  setHeader(&pPort->omxConfigMirror, sizeof(OMX_CONFIG_MIRRORTYPE));
  pPort->omxConfigMirror.nPortIndex = OMX_BASE_SINK_INPUTPORT_INDEX;
  pPort->omxConfigMirror.eMirror = OMX_MirrorNone;  //Default: No mirroring

  setHeader(&pPort->omxConfigScale, sizeof(OMX_CONFIG_SCALEFACTORTYPE));
  pPort->omxConfigScale.nPortIndex = OMX_BASE_SINK_INPUTPORT_INDEX;
  pPort->omxConfigScale.xWidth = pPort->omxConfigScale.xHeight = 0x10000;  //Default: No scaling (scale factor = 1)

  setHeader(&pPort->omxConfigOutputPosition, sizeof(OMX_CONFIG_POINTTYPE));
  pPort->omxConfigOutputPosition.nPortIndex = OMX_BASE_SINK_INPUTPORT_INDEX;
  pPort->omxConfigOutputPosition.nX = pPort->omxConfigOutputPosition.nY = 0; //Default: No shift in output position (0,0)

  /** set the function pointers */
  omx_xvideo_sink_component_Private->destructor = omx_xvideo_sink_component_Destructor;
  omx_xvideo_sink_component_Private->BufferMgmtCallback = omx_xvideo_sink_component_BufferMgmtCallback;
  openmaxStandComp->SetParameter = omx_xvideo_sink_component_SetParameter;
  openmaxStandComp->GetParameter = omx_xvideo_sink_component_GetParameter;
  omx_xvideo_sink_component_Private->messageHandler = omx_xvideo_sink_component_MessageHandler;

  omx_xvideo_sink_component_Private->bIsXVideoInit = OMX_FALSE;
  if(!omx_xvideo_sink_component_Private->xvideoSyncSem) {
    omx_xvideo_sink_component_Private->xvideoSyncSem = calloc(1,sizeof(tsem_t));
    if(omx_xvideo_sink_component_Private->xvideoSyncSem == NULL) {
      return OMX_ErrorInsufficientResources;
    }
    tsem_init(omx_xvideo_sink_component_Private->xvideoSyncSem, 0);
  }

  noxvideo_sinkInstance++;
  if(noxvideo_sinkInstance > MAX_COMPONENT_XVIDEOSINK) {
    DEBUG(DEB_LEV_ERR, "Reached Max Instances %d\n",(int)noxvideo_sinkInstance);
    return OMX_ErrorInsufficientResources;
  }

  return err;
}
/** The Constructor of the video decoder component
  * @param openmaxStandComp the component handle to be constructed
  * @param cComponentName is the name of the constructed component
  */
OMX_ERRORTYPE omx_shvpudec_component_Constructor(OMX_COMPONENTTYPE *openmaxStandComp,OMX_STRING cComponentName) {

  OMX_ERRORTYPE eError = OMX_ErrorNone;  
  omx_shvpudec_component_PrivateType* omx_shvpudec_component_Private;
  omx_base_video_PortType *inPort,*outPort;
  OMX_U32 i;

  if (!openmaxStandComp->pComponentPrivate) {
    DEBUG(DEB_LEV_FUNCTION_NAME, "In %s, allocating component\n", __func__);
    openmaxStandComp->pComponentPrivate = calloc(1, sizeof(omx_shvpudec_component_PrivateType));
    if(openmaxStandComp->pComponentPrivate == NULL) {
      return OMX_ErrorInsufficientResources;
    }
  } else {
    DEBUG(DEB_LEV_FUNCTION_NAME, "In %s, Error Component %x Already Allocated\n", __func__, (int)openmaxStandComp->pComponentPrivate);
  }

  omx_shvpudec_component_Private = openmaxStandComp->pComponentPrivate;
  omx_shvpudec_component_Private->ports = NULL;

  eError = omx_base_filter_Constructor(openmaxStandComp, cComponentName);

  omx_shvpudec_component_Private->sPortTypesParam[OMX_PortDomainVideo].nStartPortNumber = 0;
  omx_shvpudec_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts = 2;

  /** Allocate Ports and call port constructor. */
  if (omx_shvpudec_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts && !omx_shvpudec_component_Private->ports) {
    omx_shvpudec_component_Private->ports = calloc(omx_shvpudec_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts, sizeof(omx_base_PortType *));
    if (!omx_shvpudec_component_Private->ports) {
      return OMX_ErrorInsufficientResources;
    }
    for (i=0; i < omx_shvpudec_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts; i++) {
      omx_shvpudec_component_Private->ports[i] = calloc(1, sizeof(omx_base_video_PortType));
      if (!omx_shvpudec_component_Private->ports[i]) {
        return OMX_ErrorInsufficientResources;
      }
    }
  }

  base_video_port_Constructor(openmaxStandComp, &omx_shvpudec_component_Private->ports[0], 0, OMX_TRUE);
  base_video_port_Constructor(openmaxStandComp, &omx_shvpudec_component_Private->ports[1], 1, OMX_FALSE);

  /** here we can override whatever defaults the base_component constructor set
    * e.g. we can override the function pointers in the private struct  
    */

  /** Domain specific section for the ports.   
    * first we set the parameter common to both formats
    */
  //common parameters related to input port
  inPort = (omx_base_video_PortType *)omx_shvpudec_component_Private->ports[OMX_BASE_FILTER_INPUTPORT_INDEX];
  inPort->sPortParam.nBufferSize = DEFAULT_OUT_BUFFER_SIZE;
  inPort->sPortParam.format.video.xFramerate = 25;

  //common parameters related to output port
  outPort = (omx_base_video_PortType *)omx_shvpudec_component_Private->ports[OMX_BASE_FILTER_OUTPUTPORT_INDEX];
  outPort->sPortParam.format.video.eColorFormat = OUTPUT_DECODED_COLOR_FMT;
  outPort->sPortParam.nBufferSize = DEFAULT_VIDEO_OUTPUT_BUF_SIZE;
  outPort->sPortParam.format.video.xFramerate = 25;

  /** settings of output port parameter definition */
  outPort->sVideoParam.eColorFormat = OUTPUT_DECODED_COLOR_FMT;
  outPort->sVideoParam.xFramerate = 25;

  /** now it's time to know the video coding type of the component */
  if(!strcmp(cComponentName, VIDEO_DEC_MPEG4_NAME)) { 
    omx_shvpudec_component_Private->video_coding_type = OMX_VIDEO_CodingMPEG4;
  } else if(!strcmp(cComponentName, VIDEO_DEC_H264_NAME)) { 
    omx_shvpudec_component_Private->video_coding_type = OMX_VIDEO_CodingAVC;
  } else if (!strcmp(cComponentName, VIDEO_DEC_BASE_NAME)) {
    omx_shvpudec_component_Private->video_coding_type = OMX_VIDEO_CodingUnused;
  } else {
    // IL client specified an invalid component name 
    return OMX_ErrorInvalidComponentName;
  }  

  if(!omx_shvpudec_component_Private->avCodecSyncSem) {
    omx_shvpudec_component_Private->avCodecSyncSem = calloc(1,sizeof(tsem_t));
    if(omx_shvpudec_component_Private->avCodecSyncSem == NULL) {
      return OMX_ErrorInsufficientResources;
    }
    tsem_init(omx_shvpudec_component_Private->avCodecSyncSem, 0);
  }

  SetInternalVideoParameters(openmaxStandComp);

  //omx_shvpudec_component_Private->eOutFramePixFmt = PIX_FMT_YUV420P;

  if(omx_shvpudec_component_Private->video_coding_type == OMX_VIDEO_CodingMPEG4) {
    omx_shvpudec_component_Private->ports[OMX_BASE_FILTER_INPUTPORT_INDEX]->sPortParam.format.video.eCompressionFormat = OMX_VIDEO_CodingMPEG4;
  } else {
    omx_shvpudec_component_Private->ports[OMX_BASE_FILTER_INPUTPORT_INDEX]->sPortParam.format.video.eCompressionFormat = OMX_VIDEO_CodingAVC;
  }

  /** general configuration irrespective of any video formats
    * setting other parameters of omx_shvpudec_component_private  
    */
  omx_shvpudec_component_Private->decoder = NULL;
  omx_shvpudec_component_Private->avcodecReady = OMX_FALSE;
  //omx_shvpudec_component_Private->extradata = NULL;
  //omx_shvpudec_component_Private->extradata_size = 0;
  omx_shvpudec_component_Private->BufferMgmtCallback = omx_shvpudec_component_BufferMgmtCallback;

  /** initializing the codec context etc that was done earlier by ffmpeglibinit function */
  omx_shvpudec_component_Private->messageHandler = omx_shvpudec_component_MessageHandler;
  omx_shvpudec_component_Private->destructor = omx_shvpudec_component_Destructor;
  openmaxStandComp->SetParameter = omx_shvpudec_component_SetParameter;
  openmaxStandComp->GetParameter = omx_shvpudec_component_GetParameter;
  openmaxStandComp->SetConfig    = omx_shvpudec_component_SetConfig;
  openmaxStandComp->ComponentRoleEnum = omx_shvpudec_component_ComponentRoleEnum;
  openmaxStandComp->GetExtensionIndex = omx_shvpudec_component_GetExtensionIndex;

  noVideoDecInstance++;

  if(noVideoDecInstance > MAX_COMPONENT_VIDEODEC) {
    return OMX_ErrorInsufficientResources;
  }
  return eError;
}
/** The Constructor
 */
OMX_ERRORTYPE omx_parser3gp_component_Constructor(OMX_COMPONENTTYPE *openmaxStandComp,OMX_STRING cComponentName) {

  OMX_ERRORTYPE err = OMX_ErrorNone;
  omx_base_video_PortType *pPortV;
  omx_base_audio_PortType *pPortA;
  omx_parser3gp_component_PrivateType* omx_parser3gp_component_Private;
  DEBUG(DEB_LEV_FUNCTION_NAME,"In %s \n",__func__);

  if (!openmaxStandComp->pComponentPrivate) {
    openmaxStandComp->pComponentPrivate = calloc(1, sizeof(omx_parser3gp_component_PrivateType));
    if(openmaxStandComp->pComponentPrivate == NULL) {
      return OMX_ErrorInsufficientResources;
    }
  }

  /*Assign size of the derived port class,so that proper memory for port class can be allocated*/
  omx_parser3gp_component_Private = openmaxStandComp->pComponentPrivate;
  omx_parser3gp_component_Private->ports = NULL;

  err = omx_base_source_Constructor(openmaxStandComp, cComponentName);

  omx_parser3gp_component_Private->sPortTypesParam[OMX_PortDomainVideo].nStartPortNumber = 0;
  omx_parser3gp_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts = 1;

  omx_parser3gp_component_Private->sPortTypesParam[OMX_PortDomainAudio].nStartPortNumber = 1;
  omx_parser3gp_component_Private->sPortTypesParam[OMX_PortDomainAudio].nPorts = 1;

  omx_parser3gp_component_Private->sPortTypesParam[OMX_PortDomainOther].nStartPortNumber = 2;
  omx_parser3gp_component_Private->sPortTypesParam[OMX_PortDomainOther].nPorts = 1;

   /** Allocate Ports and call port constructor. */
  if ((omx_parser3gp_component_Private->sPortTypesParam[OMX_PortDomainAudio].nPorts  +
       omx_parser3gp_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts +
       omx_parser3gp_component_Private->sPortTypesParam[OMX_PortDomainOther].nPorts ) && !omx_parser3gp_component_Private->ports) {
       omx_parser3gp_component_Private->ports = calloc((omx_parser3gp_component_Private->sPortTypesParam[OMX_PortDomainAudio].nPorts  +
                                                        omx_parser3gp_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts +
                                                        omx_parser3gp_component_Private->sPortTypesParam[OMX_PortDomainOther].nPorts ), sizeof(omx_base_PortType *));
    if (!omx_parser3gp_component_Private->ports) {
      return OMX_ErrorInsufficientResources;
    }
    /* allocate video port*/
   omx_parser3gp_component_Private->ports[VIDEO_PORT_INDEX] = calloc(1, sizeof(omx_base_video_PortType));
   if (!omx_parser3gp_component_Private->ports[VIDEO_PORT_INDEX])
       return OMX_ErrorInsufficientResources;
   /* allocate audio port*/
   omx_parser3gp_component_Private->ports[AUDIO_PORT_INDEX] = calloc(1, sizeof(omx_base_audio_PortType));
   if (!omx_parser3gp_component_Private->ports[AUDIO_PORT_INDEX])
       return OMX_ErrorInsufficientResources;
   /* allocate clock port*/
   omx_parser3gp_component_Private->ports[CLOCK_PORT_INDEX] = calloc(1, sizeof(omx_base_clock_PortType));
   if (!omx_parser3gp_component_Private->ports[CLOCK_PORT_INDEX])
     return OMX_ErrorInsufficientResources;

  }

  base_video_port_Constructor(openmaxStandComp, &omx_parser3gp_component_Private->ports[VIDEO_PORT_INDEX], VIDEO_PORT_INDEX, OMX_FALSE);
  base_audio_port_Constructor(openmaxStandComp, &omx_parser3gp_component_Private->ports[AUDIO_PORT_INDEX], AUDIO_PORT_INDEX, OMX_FALSE);
  base_clock_port_Constructor(openmaxStandComp, &omx_parser3gp_component_Private->ports[CLOCK_PORT_INDEX], CLOCK_PORT_INDEX, OMX_TRUE);
  omx_parser3gp_component_Private->ports[CLOCK_PORT_INDEX]->sPortParam.bEnabled = OMX_FALSE;

  pPortV = (omx_base_video_PortType *) omx_parser3gp_component_Private->ports[VIDEO_PORT_INDEX];
  pPortA = (omx_base_audio_PortType *) omx_parser3gp_component_Private->ports[AUDIO_PORT_INDEX];

  /*Input pPort buffer size is equal to the size of the output buffer of the previous component*/
  pPortV->sPortParam.nBufferSize = DEFAULT_OUT_BUFFER_SIZE;
  pPortA->sPortParam.nBufferSize = DEFAULT_IN_BUFFER_SIZE;

  omx_parser3gp_component_Private->BufferMgmtCallback = omx_parser3gp_component_BufferMgmtCallback;
  omx_parser3gp_component_Private->BufferMgmtFunction = omx_base_source_twoport_BufferMgmtFunction;

  setHeader(&omx_parser3gp_component_Private->sTimeStamp, sizeof(OMX_TIME_CONFIG_TIMESTAMPTYPE));
  omx_parser3gp_component_Private->sTimeStamp.nPortIndex=0;
  omx_parser3gp_component_Private->sTimeStamp.nTimestamp=0x0;

  omx_parser3gp_component_Private->destructor = omx_parser3gp_component_Destructor;
  omx_parser3gp_component_Private->messageHandler = omx_parser3gp_component_MessageHandler;

  noParser3gpInstance++;
  if(noParser3gpInstance > MAX_COMPONENT_PARSER_3GP) {
    return OMX_ErrorInsufficientResources;
  }

  openmaxStandComp->SetParameter  = omx_parser3gp_component_SetParameter;
  openmaxStandComp->GetParameter  = omx_parser3gp_component_GetParameter;
  openmaxStandComp->SetConfig     = omx_parser3gp_component_SetConfig;
  openmaxStandComp->GetExtensionIndex = omx_parser3gp_component_GetExtensionIndex;

  /* Write in the default paramenters */

  omx_parser3gp_component_Private->pTmpOutputBuffer = calloc(1,sizeof(OMX_BUFFERHEADERTYPE));
  omx_parser3gp_component_Private->pTmpOutputBuffer->pBuffer = calloc(1,DEFAULT_OUT_BUFFER_SIZE);
  omx_parser3gp_component_Private->pTmpOutputBuffer->nFilledLen=0;
  omx_parser3gp_component_Private->pTmpOutputBuffer->nAllocLen=DEFAULT_OUT_BUFFER_SIZE;
  omx_parser3gp_component_Private->pTmpOutputBuffer->nOffset=0;

  omx_parser3gp_component_Private->avformatReady      = OMX_FALSE;
  omx_parser3gp_component_Private->isFirstBufferAudio = OMX_TRUE;
  omx_parser3gp_component_Private->isFirstBufferVideo = OMX_TRUE;

  if(!omx_parser3gp_component_Private->avformatSyncSem) {
    omx_parser3gp_component_Private->avformatSyncSem = calloc(1,sizeof(tsem_t));
    if(omx_parser3gp_component_Private->avformatSyncSem == NULL) return OMX_ErrorInsufficientResources;
    tsem_init(omx_parser3gp_component_Private->avformatSyncSem, 0);
  }
  omx_parser3gp_component_Private->sInputFileName = malloc(DEFAULT_FILENAME_LENGTH);
  /*Default Coding type*/
  omx_parser3gp_component_Private->video_coding_type = OMX_VIDEO_CodingAVC;
  omx_parser3gp_component_Private->audio_coding_type = OMX_AUDIO_CodingMP3;
  av_register_all();  /* without this file opening gives an error */

  return err;
}
int main(int argc, char** argv) {

    OMX_ERRORTYPE err;
    int argn_dec;
    OMX_STRING full_component_name;
    int isRate=0,isChannel=0;
    OMX_AUDIO_PARAM_PCMMODETYPE sPCMModeParam;
    if(argc < 2) {
        display_help();
    } else {
        flagIsOutputExpected = 0;
        flagDecodedOutputReceived = 0;
        flagIsVolCompRequested = 0;
        flagSetupTunnel = 0;
        flagIsSinkRequested = 0;

        argn_dec = 1;
        while (argn_dec < argc) {
            if (*(argv[argn_dec]) == '-') {
                if (flagIsOutputExpected) {
                    display_help();
                }
                switch (*(argv[argn_dec] + 1)) {
                case 'h' :
                    display_help();
                    break;
                case 't' :
                    flagSetupTunnel = 1;
                    flagIsSinkRequested = 1;
                    flagIsVolCompRequested = 1;
                    break;
                case 's':
                    flagIsSinkRequested = 1;
                    break;
                case 'o':
                    flagIsOutputExpected = 1;
                    break;
                case 'v':
                    flagIsVolCompRequested = 1;
                    break;
                case 'r' :
                    isRate = 1;
                    break;
                case 'n' :
                    isChannel = 1;
                    break;
                default:
                    display_help();
                }
            } else {
                if (flagIsOutputExpected) {
                    if(strstr(argv[argn_dec], ".pcm") == NULL) {
                        output_file = malloc(strlen(argv[argn_dec]) + 5);
                        strcpy(output_file,argv[argn_dec]);
                        strcat(output_file, ".pcm");
                    } else {
                        output_file = malloc(strlen(argv[argn_dec]) + 1);
                        strcpy(output_file,argv[argn_dec]);
                    }
                    flagIsOutputExpected = 0;
                    flagDecodedOutputReceived = 1;
                } else if(isRate) {
                    rate=atoi(argv[argn_dec]);
                    isRate=0;
                    if(rate <0 || rate >48000) {
                        DEBUG(DEB_LEV_ERR, "Bad Parameter rate\n");
                        display_help();
                    }
                } else if(isChannel) {
                    channel=atoi(argv[argn_dec]);
                    isChannel = 0;
                    if(channel <0 || channel >6) {
                        DEBUG(DEB_LEV_ERR, "Bad Parameter channel\n");
                        display_help();
                    }
                }
            }
            argn_dec++;
        }

        /** if volume componenterter component is not selected then sink component will not work, even if specified */
        if(!flagIsVolCompRequested && flagIsSinkRequested) {
            DEBUG(DEB_LEV_ERR, "You requested for sink - not producing any output file\n");
            flagIsVolCompRequested = 1;
            flagDecodedOutputReceived = 0;
        }

        /** output file name check */
        //case 1 - user did not specify any output file
        if(!flagIsOutputExpected && !flagDecodedOutputReceived && !flagIsSinkRequested) {
            DEBUG(DEB_LEV_ERR,"\n you did not enter any output file name");
            output_file = malloc(20);
            strcpy(output_file,"output.pcm");
            DEBUG(DEB_LEV_ERR,"\n the decoded output file name will be %s \n", output_file);
        } else if(flagDecodedOutputReceived) {
            if(flagIsSinkRequested || flagSetupTunnel) {
                flagDecodedOutputReceived = 0;
                DEBUG(DEB_LEV_ERR, "Sink Requested or Components are tunneled. No FILE Output will be produced\n");
            } else {
                //case 2 - user has given wrong format
                if(flagIsVolCompRequested && strstr(output_file, ".pcm") == NULL) {
                    output_file[strlen(output_file) - strlen(strstr(output_file, "."))] = '\0';
                    strcat(output_file, ".rgb");
                    DEBUG(DEB_LEV_ERR,"\n volume component option is selected - so the output file is %s \n", output_file);
                }
            }
        }
        if(flagSetupTunnel) {
            DEBUG(DEFAULT_MESSAGES,"The components are tunneled between themselves\n");
        }
    }

    if(!flagIsSinkRequested) {
        outfile = fopen(output_file, "wb");
        if(outfile == NULL) {
            DEBUG(DEB_LEV_ERR, "Error in opening output file %s\n", output_file);
            exit(1);
        }
    }

    /* Initialize application private data */
    appPriv = malloc(sizeof(appPrivateType));
    appPriv->sourceEventSem = malloc(sizeof(tsem_t));
    if(flagIsVolCompRequested == 1) {
        if(flagIsSinkRequested == 1) {
            appPriv->alsasinkEventSem = malloc(sizeof(tsem_t));
        }
        appPriv->volumeEventSem = malloc(sizeof(tsem_t));
    }
    appPriv->eofSem = malloc(sizeof(tsem_t));
    tsem_init(appPriv->sourceEventSem, 0);
    if(flagIsVolCompRequested == 1) {
        if(flagIsSinkRequested == 1) {
            tsem_init(appPriv->alsasinkEventSem, 0);
        }
        tsem_init(appPriv->volumeEventSem, 0);
    }
    tsem_init(appPriv->eofSem, 0);

    DEBUG(DEB_LEV_SIMPLE_SEQ, "Init the Omx core\n");
    err = OMX_Init();
    if (err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR, "The OpenMAX core can not be initialized. Exiting...\n");
        exit(1);
    } else {
        DEBUG(DEB_LEV_SIMPLE_SEQ, "Omx core is initialized \n");
    }

    DEBUG(DEFAULT_MESSAGES, "------------------------------------\n");
    test_OMX_ComponentNameEnum();
    DEBUG(DEFAULT_MESSAGES, "------------------------------------\n");
    test_OMX_RoleEnum(COMPONENT_NAME_BASE);
    DEBUG(DEFAULT_MESSAGES, "------------------------------------\n");
    test_OMX_ComponentEnumByRole(BASE_ROLE);
    DEBUG(DEFAULT_MESSAGES, "------------------------------------\n");
    test_OpenClose(COMPONENT_NAME_BASE);
    DEBUG(DEFAULT_MESSAGES, "------------------------------------\n");


    full_component_name = malloc(OMX_MAX_STRINGNAME_SIZE);
    strcpy(full_component_name, "OMX.st.alsa.alsasrc");

    DEBUG(DEFAULT_MESSAGES, "The component selected for decoding is %s\n", full_component_name);

    /** getting audio source handle */
    err = OMX_GetHandle(&appPriv->audiosrchandle, full_component_name, NULL, &audiosrccallbacks);
    if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR, "No audio source component found. Exiting...\n");
        exit(1);
    } else {
        DEBUG(DEFAULT_MESSAGES, "Found The component for capturing is %s\n", full_component_name);
    }

    /** getting volume componenterter component handle, if specified */
    if(flagIsVolCompRequested == 1) {
        err = OMX_GetHandle(&appPriv->volume_handle, "OMX.st.volume.component", NULL, &volume_callbacks);
        if(err != OMX_ErrorNone) {
            DEBUG(DEB_LEV_ERR, "No volume componenterter component found. Exiting...\n");
            exit(1);
        } else {
            DEBUG(DEFAULT_MESSAGES, "Found The component for volume componenterter \n");
        }

        /** getting sink component handle - if reqd' */
        if(flagIsSinkRequested == 1) {
            err = OMX_GetHandle(&appPriv->alsasink_handle, "OMX.st.alsa.alsasink", NULL, &alsasink_callbacks);
            if(err != OMX_ErrorNone) {
                DEBUG(DEB_LEV_ERR, "No audio sink component component found. Exiting...\n");
                exit(1);
            } else {
                DEBUG(DEFAULT_MESSAGES, "Found The audio sink component for volume componenterter \n");
            }
        }
    }

    if(rate >0 || channel >0) {
        setHeader(&sPCMModeParam, sizeof(OMX_AUDIO_PARAM_PCMMODETYPE));
        err = OMX_GetParameter(appPriv->audiosrchandle,OMX_IndexParamAudioPcm,&sPCMModeParam);
        if (err != OMX_ErrorNone) {
            DEBUG(DEB_LEV_ERR, "Err in GetParameter OMX_AUDIO_PARAM_PCMMODETYPE in AlsaSrc. Exiting...\n");
            exit(1);
        }
        sPCMModeParam.nChannels = (channel >0 ) ? channel:sPCMModeParam.nChannels;
        sPCMModeParam.nSamplingRate = (rate >0 ) ? rate:sPCMModeParam.nSamplingRate;
        err = OMX_SetParameter(appPriv->audiosrchandle,OMX_IndexParamAudioPcm,&sPCMModeParam);
        if (err != OMX_ErrorNone) {
            DEBUG(DEB_LEV_ERR, "Err in SetParameter OMX_AUDIO_PARAM_PCMMODETYPE in AlsaSrc. Exiting...\n");
            exit(1);
        }
        if(flagIsSinkRequested) {
            err = OMX_SetParameter(appPriv->alsasink_handle,OMX_IndexParamAudioPcm,&sPCMModeParam);
            if (err != OMX_ErrorNone) {
                DEBUG(DEB_LEV_ERR, "Err in SetParameter OMX_AUDIO_PARAM_PCMMODETYPE in AlsaSink. Exiting...\n");
                exit(1);
            }
        }
    } else if(flagIsSinkRequested) {
        setHeader(&sPCMModeParam, sizeof(OMX_AUDIO_PARAM_PCMMODETYPE));
        err = OMX_GetParameter(appPriv->audiosrchandle,OMX_IndexParamAudioPcm,&sPCMModeParam);
        if (err != OMX_ErrorNone) {
            DEBUG(DEB_LEV_ERR, "Err in GetParameter OMX_AUDIO_PARAM_PCMMODETYPE in AlsaSrc. Exiting...\n");
            exit(1);
        }
        err = OMX_SetParameter(appPriv->alsasink_handle,OMX_IndexParamAudioPcm,&sPCMModeParam);
        if (err != OMX_ErrorNone) {
            DEBUG(DEB_LEV_ERR, "Err in SetParameter OMX_AUDIO_PARAM_PCMMODETYPE in AlsaSink. Exiting...\n");
            exit(1);
        }
    }

    /** output buffer size calculation based on input dimension speculation */
    DEBUG(DEB_LEV_SIMPLE_SEQ, "\n buffer_out_size : %d \n", (int)buffer_out_size);

    /** if tunneling option is given then set up the tunnel between the components */
    if (flagSetupTunnel) {
        DEBUG(DEB_LEV_SIMPLE_SEQ, "Setting up Tunnel\n");
        err = OMX_SetupTunnel(appPriv->audiosrchandle, 0, appPriv->volume_handle, 0);
        if(err != OMX_ErrorNone) {
            DEBUG(DEB_LEV_ERR, "Set up Tunnel between audio src & volume component Failed\n");
            exit(1);
        }
        err = OMX_SetupTunnel(appPriv->volume_handle, 1, appPriv->alsasink_handle, 0);
        if(err != OMX_ErrorNone) {
            DEBUG(DEB_LEV_ERR, "Set up Tunnel between volume component & audio sink Failed\n");
            exit(1);
        }
        DEBUG(DEFAULT_MESSAGES, "Set up Tunnel Completed\n");
    }

    /** sending command to audio source component to go to idle state */
    err = OMX_SendCommand(appPriv->audiosrchandle, OMX_CommandStateSet, OMX_StateIdle, NULL);

    /** in tunnel case, change the volume component and sink comp state to idle */
    if(flagIsVolCompRequested && flagSetupTunnel) {
        err = OMX_SendCommand(appPriv->volume_handle, OMX_CommandStateSet, OMX_StateIdle, NULL);
        if(flagIsSinkRequested && flagSetupTunnel) {
            err = OMX_SendCommand(appPriv->alsasink_handle, OMX_CommandStateSet, OMX_StateIdle, NULL);
        }
    }

    if(flagSetupTunnel) {
        if(flagIsSinkRequested) {
            tsem_down(appPriv->alsasinkEventSem);
        }
        if(flagIsVolCompRequested) {
            tsem_down(appPriv->volumeEventSem);
        }
    }

    /** if tunneling option is not given then allocate buffers on audio source output port */
    if (!flagSetupTunnel) {
        pOutBuffer[0] = pOutBuffer[1] = NULL;
        err = OMX_AllocateBuffer(appPriv->audiosrchandle, &pOutBuffer[0], 0, NULL, buffer_out_size);
        err = OMX_AllocateBuffer(appPriv->audiosrchandle, &pOutBuffer[1], 0, NULL, buffer_out_size);
    }

    DEBUG(DEB_LEV_SIMPLE_SEQ, "Before locking on idle wait semaphore\n");
    tsem_down(appPriv->sourceEventSem);
    DEBUG(DEB_LEV_SIMPLE_SEQ, "source Sem free\n");

    if(!flagSetupTunnel) {
        if(flagIsVolCompRequested == 1) {
            pOutBufferVolc[0] = pOutBufferVolc[1] = NULL;
            err = OMX_SendCommand(appPriv->volume_handle, OMX_CommandStateSet, OMX_StateIdle, NULL);

            /** in non tunneled case, using buffers in volume component input port, allocated by audio dec component output port */
            err = OMX_UseBuffer(appPriv->volume_handle, &pInBufferVolc[0], 0, NULL, buffer_out_size, pOutBuffer[0]->pBuffer);
            if(err != OMX_ErrorNone) {
                DEBUG(DEB_LEV_ERR, "Unable to use the volume component comp allocate buffer\n");
                exit(1);
            }
            err = OMX_UseBuffer(appPriv->volume_handle, &pInBufferVolc[1], 0, NULL, buffer_out_size, pOutBuffer[1]->pBuffer);
            if(err != OMX_ErrorNone) {
                DEBUG(DEB_LEV_ERR, "Unable to use the volume component comp allocate buffer\n");
                exit(1);
            }

            /** allocating buffers in the volume componenterter compoennt output port */

            err = OMX_AllocateBuffer(appPriv->volume_handle, &pOutBufferVolc[0], 1, NULL, buffer_out_size);
            if(err != OMX_ErrorNone) {
                DEBUG(DEB_LEV_ERR, "Unable to allocate buffer in volume component\n");
                exit(1);
            }
            err = OMX_AllocateBuffer(appPriv->volume_handle, &pOutBufferVolc[1], 1, NULL, buffer_out_size);
            if(err != OMX_ErrorNone) {
                DEBUG(DEB_LEV_ERR, "Unable to allocate buffer in colro conv\n");
                exit(1);
            }

            DEBUG(DEB_LEV_SIMPLE_SEQ, "Before locking on idle wait semaphore\n");
            tsem_down(appPriv->volumeEventSem);
            DEBUG(DEFAULT_MESSAGES, "volume Event Sem free\n");

            if(flagIsSinkRequested == 1) {
                err = OMX_SendCommand(appPriv->alsasink_handle, OMX_CommandStateSet, OMX_StateIdle, NULL);
                err = OMX_UseBuffer(appPriv->alsasink_handle, &pInBufferSink[0], 0, NULL, buffer_out_size, pOutBufferVolc[0]->pBuffer);
                if(err != OMX_ErrorNone) {
                    DEBUG(DEB_LEV_ERR, "Unable to use the alsasink_handle comp allocate buffer\n");
                    exit(1);
                }
                err = OMX_UseBuffer(appPriv->alsasink_handle, &pInBufferSink[1], 0, NULL, buffer_out_size, pOutBufferVolc[1]->pBuffer);
                if(err != OMX_ErrorNone) {
                    DEBUG(DEB_LEV_ERR, "Unable to use the alsasink_handle comp allocate buffer\n");
                    exit(1);
                }

                DEBUG(DEB_LEV_SIMPLE_SEQ, "Before locking on idle wait semaphore\n");
                tsem_down(appPriv->alsasinkEventSem);
                DEBUG(DEB_LEV_SIMPLE_SEQ, "audio sink comp Sem free\n");
            }
        }

        if(flagIsVolCompRequested == 1) {
            err = OMX_SendCommand(appPriv->volume_handle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
            tsem_down(appPriv->volumeEventSem);
            if(flagIsSinkRequested == 1) {
                err = OMX_SendCommand(appPriv->alsasink_handle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
                tsem_down(appPriv->alsasinkEventSem);
            }
        }
    }

    /** send command to change color onv and sink comp in executing state */
    if(flagIsVolCompRequested == 1 && flagSetupTunnel) {
        err = OMX_SendCommand(appPriv->volume_handle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
        tsem_down(appPriv->volumeEventSem);
        if(flagIsSinkRequested == 1) {
            err = OMX_SendCommand(appPriv->alsasink_handle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
            tsem_down(appPriv->alsasinkEventSem);
        }
    }

    /** sending command to audio source component to go to executing state */
    err = OMX_SendCommand(appPriv->audiosrchandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
    tsem_down(appPriv->sourceEventSem);

    if(flagIsVolCompRequested == 1 && !flagSetupTunnel) {
        err = OMX_FillThisBuffer(appPriv->volume_handle, pOutBufferVolc[0]);
        err = OMX_FillThisBuffer(appPriv->volume_handle, pOutBufferVolc[1]);
        DEBUG(DEFAULT_MESSAGES, "---> After fill this buffer function calls to the volume component output buffers\n");
    }
    if (!flagSetupTunnel) {
        err = OMX_FillThisBuffer(appPriv->audiosrchandle, pOutBuffer[0]);
        err = OMX_FillThisBuffer(appPriv->audiosrchandle, pOutBuffer[1]);
    }

    DEBUG(DEB_LEV_SIMPLE_SEQ, "---> Before locking on condition and sourceMutex\n");

    DEBUG(DEFAULT_MESSAGES,"Enter 'q' or 'Q' to exit\n");

    while(1) {
        if('Q' == toupper(getchar())) {
            DEBUG(DEFAULT_MESSAGES,"Stoping capture\n");
            bEOS = OMX_TRUE;
            usleep(10000);
            break;
        }
    }

    DEBUG(DEFAULT_MESSAGES, "The execution of the audio decoding process is terminated\n");

    /** state change of all components from executing to idle */
    err = OMX_SendCommand(appPriv->audiosrchandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
    if(flagIsVolCompRequested == 1) {
        err = OMX_SendCommand(appPriv->volume_handle, OMX_CommandStateSet, OMX_StateIdle, NULL);
        if(flagIsSinkRequested == 1) {
            err = OMX_SendCommand(appPriv->alsasink_handle, OMX_CommandStateSet, OMX_StateIdle, NULL);
        }
    }

    tsem_down(appPriv->sourceEventSem);
    if(flagIsVolCompRequested == 1) {
        tsem_down(appPriv->volumeEventSem);
        if(flagIsSinkRequested == 1) {
            tsem_down(appPriv->alsasinkEventSem);
        }
    }

    DEBUG(DEFAULT_MESSAGES, "All audio components Transitioned to Idle\n");

    /** sending command to all components to go to loaded state */
    err = OMX_SendCommand(appPriv->audiosrchandle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
    if(flagIsVolCompRequested == 1) {
        err = OMX_SendCommand(appPriv->volume_handle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
        if(flagIsSinkRequested == 1) {
            err = OMX_SendCommand(appPriv->alsasink_handle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
        }
    }

    /** freeing buffers of volume component and sink component */
    if(flagIsVolCompRequested == 1 && !flagSetupTunnel) {

        DEBUG(DEB_LEV_SIMPLE_SEQ, "volume component to loaded\n");
        err = OMX_FreeBuffer(appPriv->volume_handle, 0, pInBufferVolc[0]);
        err = OMX_FreeBuffer(appPriv->volume_handle, 0, pInBufferVolc[1]);

        err = OMX_FreeBuffer(appPriv->volume_handle, 1, pOutBufferVolc[0]);
        err = OMX_FreeBuffer(appPriv->volume_handle, 1, pOutBufferVolc[1]);

        if(flagIsSinkRequested == 1) {
            DEBUG(DEB_LEV_SIMPLE_SEQ, "Audio sink to loaded\n");
            err = OMX_FreeBuffer(appPriv->alsasink_handle, 0, pInBufferSink[0]);
            err = OMX_FreeBuffer(appPriv->alsasink_handle, 0, pInBufferSink[1]);
        }
    }

    /** freeing buffers of audio source input ports */
    DEBUG(DEB_LEV_SIMPLE_SEQ, "Audio dec to loaded\n");
    if(!flagSetupTunnel) {
        DEBUG(DEB_LEV_PARAMS, "Free Audio dec output ports\n");
        err = OMX_FreeBuffer(appPriv->audiosrchandle, 0, pOutBuffer[0]);
        err = OMX_FreeBuffer(appPriv->audiosrchandle, 0, pOutBuffer[1]);
    }

    if(flagIsVolCompRequested == 1) {
        if(flagIsSinkRequested == 1) {
            tsem_down(appPriv->alsasinkEventSem);
        }
        tsem_down(appPriv->volumeEventSem);
    }
    tsem_down(appPriv->sourceEventSem);
    DEBUG(DEB_LEV_SIMPLE_SEQ, "All components released\n");

    OMX_FreeHandle(appPriv->audiosrchandle);
    if(flagIsVolCompRequested == 1) {
        if(flagIsSinkRequested == 1) {
            OMX_FreeHandle(appPriv->alsasink_handle);
        }
        OMX_FreeHandle(appPriv->volume_handle);
    }
    DEBUG(DEB_LEV_SIMPLE_SEQ, "audio dec freed\n");

    OMX_Deinit();

    DEBUG(DEFAULT_MESSAGES, "All components freed. Closing...\n");
    free(appPriv->sourceEventSem);
    if(flagIsVolCompRequested == 1) {
        if(flagIsSinkRequested == 1) {
            free(appPriv->alsasinkEventSem);
        }
        free(appPriv->volumeEventSem);
    }
    free(appPriv->eofSem);
    free(appPriv);

    free(full_component_name);

    /** closing the output file */
    if(!flagIsSinkRequested) {
        fclose(outfile);
    }
    if(output_file) {
        free(output_file);
    }

    return 0;
}
int main(int argc, char** argv) {

  OMX_ERRORTYPE err;
  int argn_dec;
  OMX_STRING full_component_name;

  if(argc < 2){
    display_help();
  } else {
    flagIsOutputExpected = 0;
    argn_dec = 1;
    while (argn_dec < argc) {
      if (*(argv[argn_dec]) == '-') {
        if (flagIsOutputExpected) {
          display_help();
        }
        switch (*(argv[argn_dec] + 1)) {
          case 'h' :
            display_help();
            break;
          case 'o':
            flagIsOutputExpected = 1;
            break;
          default:
            display_help();
        }
      } else {
        if (flagIsOutputExpected) {
          if(strstr(argv[argn_dec], ".yuv") == NULL && strstr(argv[argn_dec], ".rgb") == NULL) {
            output_file = malloc(strlen(argv[argn_dec]) * sizeof(char) + 5);
            strcpy(output_file,argv[argn_dec]);
            strcat(output_file, ".rgb");
          } else {
            output_file = malloc(strlen(argv[argn_dec]) * sizeof(char) + 1);
            strcpy(output_file,argv[argn_dec]);
          }
          flagIsOutputExpected = 0;
        }
      }
      argn_dec++;
    }
  }

  if(output_file==NULL) {
    output_file = malloc(30);
    strcpy(output_file,"default_camera_out.rgb");
  }

  outfile = fopen(output_file, "wb");
  if(outfile == NULL) {
    DEBUG(DEB_LEV_ERR, "Error in opening output file %s\n", output_file);
    exit(1);
  }

  /** setting input picture width to a default value (vga format) for allocation of video videosrc buffers */
  out_width = 176;
  out_height = 144;

  /* Initialize application private data */
  appPriv = malloc(sizeof(appPrivateType));
  appPriv->videosrcEventSem = malloc(sizeof(tsem_t));
  appPriv->eofSem = malloc(sizeof(tsem_t));
  tsem_init(appPriv->videosrcEventSem, 0);
  tsem_init(appPriv->eofSem, 0);

  DEBUG(DEB_LEV_SIMPLE_SEQ, "Init the Omx core\n");
  err = OMX_Init();
  if (err != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "The OpenMAX core can not be initialized. Exiting...\n");
    exit(1);
  } else {
    DEBUG(DEB_LEV_SIMPLE_SEQ, "Omx core is initialized \n");
  }

  test_OpenClose(COMPONENT_NAME);
  DEBUG(DEFAULT_MESSAGES, "------------------------------------\n");


  full_component_name = (OMX_STRING) malloc(sizeof(char*) * OMX_MAX_STRINGNAME_SIZE);
  strcpy(full_component_name, COMPONENT_NAME);


  DEBUG(DEFAULT_MESSAGES, "The component selected for capturing is %s\n", full_component_name);

  /** getting video videosrc handle */
  err = OMX_GetHandle(&appPriv->videosrchandle, full_component_name, NULL, &videosrccallbacks);
  if(err != OMX_ErrorNone){
    DEBUG(DEB_LEV_ERR, "No video videosrc component found. Exiting...\n");
    exit(1);
  } else {
    DEBUG(DEFAULT_MESSAGES, "Found The component for capturing is %s\n", full_component_name);
  }

  /** output buffer size calculation based on input dimension speculation */
  buffer_out_size = out_width * out_height * 3; //yuv420 format -- bpp = 12
  DEBUG(DEB_LEV_SIMPLE_SEQ, "\n buffer_out_size : %d \n", (int)buffer_out_size);

  /** sending command to video videosrc component to go to idle state */
  err = OMX_SendCommand(appPriv->videosrchandle, OMX_CommandStateSet, OMX_StateIdle, NULL);

  pOutBuffer1 = pOutBuffer2 = NULL;
  err = OMX_AllocateBuffer(appPriv->videosrchandle, &pOutBuffer1, 0, NULL, buffer_out_size);
  err = OMX_AllocateBuffer(appPriv->videosrchandle, &pOutBuffer2, 0, NULL, buffer_out_size);


  DEBUG(DEB_LEV_SIMPLE_SEQ, "Before locking on idle wait semaphore\n");
  tsem_down(appPriv->videosrcEventSem);
  DEBUG(DEB_LEV_SIMPLE_SEQ, "videosrc Sem free\n");

  /** sending command to video videosrc component to go to executing state */
  err = OMX_SendCommand(appPriv->videosrchandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
  tsem_down(appPriv->videosrcEventSem);

  err = OMX_FillThisBuffer(appPriv->videosrchandle, pOutBuffer1);
  err = OMX_FillThisBuffer(appPriv->videosrchandle, pOutBuffer2);

  DEBUG(DEFAULT_MESSAGES,"Waiting for  EOS\n");

  /*Capture video for 10 seconds*/
  sleep(10);
  bEOS = OMX_TRUE;
  DEBUG(DEFAULT_MESSAGES,"Set  EOS\n");
  sleep(1);
  //tsem_down(appPriv->eofSem);

  DEBUG(DEFAULT_MESSAGES, "The execution of the video capturing process is terminated\n");

  /** state change of all components from executing to idle */
  err = OMX_SendCommand(appPriv->videosrchandle, OMX_CommandStateSet, OMX_StateIdle, NULL);

  tsem_down(appPriv->videosrcEventSem);


  DEBUG(DEFAULT_MESSAGES, "All video components Transitioned to Idle\n");

  /** sending command to all components to go to loaded state */
  err = OMX_SendCommand(appPriv->videosrchandle, OMX_CommandStateSet, OMX_StateLoaded, NULL);


  /** freeing buffers of video videosrc input ports */
  DEBUG(DEB_LEV_PARAMS, "Free Video dec output ports\n");
  err = OMX_FreeBuffer(appPriv->videosrchandle, 0, pOutBuffer1);
  err = OMX_FreeBuffer(appPriv->videosrchandle, 0, pOutBuffer2);

  tsem_down(appPriv->videosrcEventSem);
  DEBUG(DEB_LEV_SIMPLE_SEQ, "All components released\n");

  OMX_FreeHandle(appPriv->videosrchandle);

  DEBUG(DEB_LEV_SIMPLE_SEQ, "video dec freed\n");

  OMX_Deinit();

  DEBUG(DEFAULT_MESSAGES, "All components freed. Closing...\n");
  free(appPriv->videosrcEventSem);

  free(appPriv->eofSem);
  free(appPriv);

  /** closing the output file */
  fclose(outfile);

  return 0;
}
/** The Constructor of the video encoder component
  * @param openmaxStandComp the component handle to be constructed
  * @param cComponentName is the name of the constructed component
  */
OMX_ERRORTYPE omx_videoenc_component_Constructor(OMX_COMPONENTTYPE *openmaxStandComp,OMX_STRING cComponentName) {

  OMX_ERRORTYPE eError = OMX_ErrorNone;  
  omx_videoenc_component_PrivateType* omx_videoenc_component_Private;
  omx_base_video_PortType *inPort,*outPort;
  OMX_U32 i;

  if (!openmaxStandComp->pComponentPrivate) {
    DEBUG(DEB_LEV_FUNCTION_NAME, "In %s, allocating component\n", __func__);
    openmaxStandComp->pComponentPrivate = calloc(1, sizeof(omx_videoenc_component_PrivateType));
    if(openmaxStandComp->pComponentPrivate == NULL) {
      return OMX_ErrorInsufficientResources;
    }
  } else {
    DEBUG(DEB_LEV_FUNCTION_NAME, "In %s, Error Component %x Already Allocated\n", __func__, (int)openmaxStandComp->pComponentPrivate);
  }

  omx_videoenc_component_Private = openmaxStandComp->pComponentPrivate;
  omx_videoenc_component_Private->ports = NULL;

  /** we could create our own port structures here
    * fixme maybe the base class could use a "port factory" function pointer?  
    */
  eError = omx_base_filter_Constructor(openmaxStandComp, cComponentName);

  omx_videoenc_component_Private->sPortTypesParam[OMX_PortDomainVideo].nStartPortNumber = 0;
  omx_videoenc_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts = 2;

  /** Allocate Ports and call port constructor. */  
  if (omx_videoenc_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts && !omx_videoenc_component_Private->ports) {
    omx_videoenc_component_Private->ports = calloc(omx_videoenc_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts, sizeof(omx_base_PortType *));
    if (!omx_videoenc_component_Private->ports) {
      return OMX_ErrorInsufficientResources;
    }
    for (i=0; i < omx_videoenc_component_Private->sPortTypesParam[OMX_PortDomainVideo].nPorts; i++) {
      omx_videoenc_component_Private->ports[i] = calloc(1, sizeof(omx_base_video_PortType));
      if (!omx_videoenc_component_Private->ports[i]) {
        return OMX_ErrorInsufficientResources;
      }
    }
  }

  base_video_port_Constructor(openmaxStandComp, &omx_videoenc_component_Private->ports[0], 0, OMX_TRUE);
  base_video_port_Constructor(openmaxStandComp, &omx_videoenc_component_Private->ports[1], 1, OMX_FALSE);

  /** Domain specific section for the ports.   
    * first we set the parameter common to both formats
    */
  //common parameters related to input port
  inPort = (omx_base_video_PortType *)omx_videoenc_component_Private->ports[OMX_BASE_FILTER_INPUTPORT_INDEX];
  inPort->sPortParam.format.video.nFrameWidth = 176;
  inPort->sPortParam.format.video.nFrameHeight = 144;
  inPort->sPortParam.nBufferSize = inPort->sPortParam.format.video.nFrameWidth*
                                   inPort->sPortParam.format.video.nFrameHeight*3/2; //YUV 420
  inPort->sPortParam.format.video.xFramerate = 25;
  inPort->sPortParam.format.video.eColorFormat = OMX_COLOR_FormatYUV420Planar;
  inPort->sVideoParam.eColorFormat = OMX_COLOR_FormatYUV420Planar;

  //common parameters related to output port
  outPort = (omx_base_video_PortType *)omx_videoenc_component_Private->ports[OMX_BASE_FILTER_OUTPUTPORT_INDEX];
  outPort->sPortParam.nBufferSize = FF_MIN_BUFFER_SIZE;
  outPort->sPortParam.format.video.xFramerate = 25;
  outPort->sPortParam.format.video.nFrameWidth = 176;
  outPort->sPortParam.format.video.nFrameHeight = 144;

  /** now it's time to know the video coding type of the component */
  if(!strcmp(cComponentName, VIDEO_ENC_MPEG4_NAME)) { 
    omx_videoenc_component_Private->video_encoding_type = OMX_VIDEO_CodingMPEG4;
  } else if (!strcmp(cComponentName, VIDEO_ENC_BASE_NAME)) {
    omx_videoenc_component_Private->video_encoding_type = OMX_VIDEO_CodingUnused;
  } else {
    // IL client specified an invalid component name 
    DEBUG(DEB_LEV_ERR, "In valid component name\n");
    return OMX_ErrorInvalidComponentName;
  }  

  if(!omx_videoenc_component_Private->avCodecSyncSem) {
    omx_videoenc_component_Private->avCodecSyncSem = calloc(1,sizeof(tsem_t));
    if(omx_videoenc_component_Private->avCodecSyncSem == NULL) {
      return OMX_ErrorInsufficientResources;
    }
    tsem_init(omx_videoenc_component_Private->avCodecSyncSem, 0);
  }

  SetInternalVideoEncParameters(openmaxStandComp);

  omx_videoenc_component_Private->eOutFramePixFmt = PIX_FMT_YUV420P;

  if(omx_videoenc_component_Private->video_encoding_type == OMX_VIDEO_CodingMPEG4) {
    omx_videoenc_component_Private->ports[OMX_BASE_FILTER_INPUTPORT_INDEX]->sPortParam.format.video.eCompressionFormat = OMX_VIDEO_CodingMPEG4;
  }

  /** general configuration irrespective of any video formats
    * setting other parameters of omx_videoenc_component_private  
    */
  omx_videoenc_component_Private->avCodec = NULL;
  omx_videoenc_component_Private->avCodecContext= NULL;
  omx_videoenc_component_Private->avcodecReady = OMX_FALSE;
  omx_videoenc_component_Private->BufferMgmtCallback = omx_videoenc_component_BufferMgmtCallback;

  /** initializing the coenc context etc that was done earlier by ffmpeglibinit function */
  omx_videoenc_component_Private->messageHandler = omx_videoenc_component_MessageHandler;
  omx_videoenc_component_Private->destructor = omx_videoenc_component_Destructor;
  openmaxStandComp->SetParameter = omx_videoenc_component_SetParameter;
  openmaxStandComp->GetParameter = omx_videoenc_component_GetParameter;
  openmaxStandComp->ComponentRoleEnum = omx_videoenc_component_ComponentRoleEnum;

  noVideoEncInstance++;

  if(noVideoEncInstance > MAX_COMPONENT_VIDEOENC) {
    return OMX_ErrorInsufficientResources;
  }
  return eError;
}
int main(int argc, char** argv) {

  OMX_PORT_PARAM_TYPE param;
  OMX_BUFFERHEADERTYPE *inBuffer1, *inBuffer2, *outBuffer1, *outBuffer2;
  int data_read1;
  int data_read2;
  OMX_PARAM_PORTDEFINITIONTYPE sPortDef;
  OMX_AUDIO_CONFIG_VOLUMETYPE sVolume;
  int gain=100;
  int argn_dec;

  /* Obtain file descriptor */
  if(argc < 2){
    display_help();
  } else {
    flagIsOutputExpected = 0;
    flagOutputReceived = 0;
    flagInputReceived = 0;
    flagIsGain = 0;

    argn_dec = 1;
    while (argn_dec<argc) {
      if (*(argv[argn_dec]) =='-') {
        if (flagIsOutputExpected) {
          display_help();
        }
        switch (*(argv[argn_dec]+1)) {
        case 'h':
          display_help();
          break;
        case 'o':
          flagIsOutputExpected = 1;
          break;
        case 'g':
          flagIsGain = 1;
          break;
        default:
          display_help();
        }
      } else {
        if (flagIsGain) {
          gain = (int)atoi(argv[argn_dec]);
          flagIsGain = 0;
          if(gain > 100) {
            DEBUG(DEFAULT_MESSAGES, "Gain should be between [0..100]\n");
            gain = 100; 
          }
        } else if (flagIsOutputExpected) {
          output_file = malloc(strlen(argv[argn_dec]) + 1);
          strcpy(output_file,argv[argn_dec]);
          flagIsOutputExpected = 0;
          flagOutputReceived = 1;
        } else {
          input_file = malloc(strlen(argv[argn_dec]) + 1);
          strcpy(input_file,argv[argn_dec]);
          flagInputReceived = 1;
        }
      }
      argn_dec++;
    }
    if (!flagInputReceived) {
      display_help();
    }
    DEBUG(DEFAULT_MESSAGES, "Input file %s", input_file);
    DEBUG(DEFAULT_MESSAGES, " to ");
    if (flagOutputReceived) {
      DEBUG(DEFAULT_MESSAGES, " %s\n", output_file);
    }
  }

 
  fd = open(input_file, O_RDONLY);
  if(fd < 0){
    perror("Error opening input file\n");
    exit(1);
  }

  if (flagOutputReceived) {
    outfile = fopen(output_file,"wb");
    if(outfile == NULL) {
      DEBUG(DEB_LEV_ERR, "Error at opening the output file");
      exit(1);
    } 
  }
   
  filesize = getFileSize(fd);
  /* Initialize application private data */
  appPriv = malloc(sizeof(appPrivateType));
  pthread_cond_init(&appPriv->condition, NULL);
  pthread_mutex_init(&appPriv->mutex, NULL);
  appPriv->eventSem = malloc(sizeof(tsem_t));
  tsem_init(appPriv->eventSem, 0);
  appPriv->eofSem = malloc(sizeof(tsem_t));
  tsem_init(appPriv->eofSem, 0);

  err = OMX_Init();
  if(err != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "OMX_Init() failed\n");
    exit(1);
  }
  /** Ask the core for a handle to the volume control component
    */
  err = OMX_GetHandle(&handle, "OMX.st.volume.component", NULL /*appPriv */, &callbacks);
  if(err != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "OMX_GetHandle failed\n");
    exit(1);
  }

  if((gain >= 0) && (gain <100)) {
    err = OMX_GetConfig(handle, OMX_IndexConfigAudioVolume, &sVolume);
    if(err!=OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR,"Error %08x In OMX_GetConfig 0 \n",err);
    }
    sVolume.sVolume.nValue = gain;
    DEBUG(DEFAULT_MESSAGES, "Setting Gain %d \n", gain);
    err = OMX_SetConfig(handle, OMX_IndexConfigAudioVolume, &sVolume);
    if(err!=OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR,"Error %08x In OMX_SetConfig 0 \n",err);
    }
  }

  /** Set the number of ports for the parameter structure */
  param.nPorts = 2;
  setHeader(&param, sizeof(OMX_PORT_PARAM_TYPE));
  err = OMX_GetParameter(handle, OMX_IndexParamAudioInit, &param);
  if(err != OMX_ErrorNone){
    DEBUG(DEB_LEV_ERR, "Error in getting OMX_PORT_PARAM_TYPE parameter\n");
    exit(1);
  }

  setHeader(&sPortDef, sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
  sPortDef.nPortIndex = 0;
  err = OMX_GetParameter(handle, OMX_IndexParamPortDefinition, &sPortDef);

  sPortDef.nBufferCountActual = 2;
  err = OMX_SetParameter(handle, OMX_IndexParamPortDefinition, &sPortDef);
  if(err != OMX_ErrorNone){
    DEBUG(DEB_LEV_ERR, "Error in getting OMX_PORT_PARAM_TYPE parameter\n");
    exit(1);
  }
  sPortDef.nPortIndex = 1;
  err = OMX_GetParameter(handle, OMX_IndexParamPortDefinition, &sPortDef);

  sPortDef.nBufferCountActual = 2;
  err = OMX_SetParameter(handle, OMX_IndexParamPortDefinition, &sPortDef);
  if(err != OMX_ErrorNone){
    DEBUG(DEB_LEV_ERR, "Error in getting OMX_PORT_PARAM_TYPE parameter\n");
    exit(1);
  }

  err = OMX_SendCommand(handle, OMX_CommandStateSet, OMX_StateIdle, NULL);

  inBuffer1 = inBuffer2 = outBuffer1 = outBuffer2 = NULL;
  err = OMX_AllocateBuffer(handle, &inBuffer1, 0, NULL, BUFFER_IN_SIZE);
  if (err != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Error on AllocateBuffer in 1%i\n", err);
    exit(1);
  }
  err = OMX_AllocateBuffer(handle, &inBuffer2, 0, NULL, BUFFER_IN_SIZE);
  if (err != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Error on AllocateBuffer in 2 %i\n", err);
    exit(1);
  }
  err = OMX_AllocateBuffer(handle, &outBuffer1, 1, NULL, BUFFER_IN_SIZE);
  if (err != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Error on AllocateBuffer out 1 %i\n", err);
    exit(1);
  }
  err = OMX_AllocateBuffer(handle, &outBuffer2, 1, NULL, BUFFER_IN_SIZE);
  if (err != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Error on AllocateBuffer out 2 %i\n", err);
    exit(1);
  }

  tsem_down(appPriv->eventSem);
  err = OMX_SendCommand(handle, OMX_CommandStateSet, OMX_StateExecuting, NULL);

  /* Wait for commands to complete */
  tsem_down(appPriv->eventSem);

  DEBUG(DEB_LEV_PARAMS, "Had buffers at:\n0x%08x\n0x%08x\n0x%08x\n0x%08x\n", 
                (int)inBuffer1->pBuffer, (int)inBuffer2->pBuffer, (int)outBuffer1->pBuffer, (int)outBuffer2->pBuffer);
  DEBUG(DEB_LEV_PARAMS, "After switch to executing\n");

  data_read1 = read(fd, inBuffer1->pBuffer, BUFFER_IN_SIZE);
  inBuffer1->nFilledLen = data_read1;
  filesize -= data_read1;

  data_read2 = read(fd, inBuffer2->pBuffer, BUFFER_IN_SIZE);
  inBuffer2->nFilledLen = data_read2;
  filesize -= data_read2;

  DEBUG(DEB_LEV_PARAMS, "Empty first  buffer %x\n", (int)inBuffer1);
  err = OMX_EmptyThisBuffer(handle, inBuffer1);
  DEBUG(DEB_LEV_PARAMS, "Empty second buffer %x\n", (int)inBuffer2);
  err = OMX_EmptyThisBuffer(handle, inBuffer2);
  
  /** Schedule a couple of buffers to be filled on the output port
    * The callback itself will re-schedule them.
    */
  err = OMX_FillThisBuffer(handle, outBuffer1);
  err = OMX_FillThisBuffer(handle, outBuffer2);

  tsem_down(appPriv->eofSem);

  err = OMX_SendCommand(handle, OMX_CommandStateSet, OMX_StateIdle, NULL);
  /* Wait for commands to complete */
  tsem_down(appPriv->eventSem);

  err = OMX_SendCommand(handle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
  err = OMX_FreeBuffer(handle, 0, inBuffer1);
  err = OMX_FreeBuffer(handle, 0, inBuffer2);
  err = OMX_FreeBuffer(handle, 1, outBuffer1);
  err = OMX_FreeBuffer(handle, 1, outBuffer2);

  /* Wait for commands to complete */
  tsem_down(appPriv->eventSem);

  OMX_FreeHandle(handle);

  free(appPriv->eventSem);
  free(appPriv);

  if (flagOutputReceived) {
    if(fclose(outfile) != 0) {
      DEBUG(DEB_LEV_ERR,"Error in closing output file\n");
      exit(1);
    }
    free(output_file);
  }

  close(fd);
  free(input_file);

  return 0;
}
OMX_ERRORTYPE OMX_ComponentInit (OMX_HANDLETYPE hComponent)
{
  OMX_ERRORTYPE err = OMX_ErrorNone;  
  OMX_COMPONENTTYPE *pHandle = NULL;
  char std_string[10]; 
  omx_jpegdec_component_PrivateType* omx_jpegdec_component_Private = NULL;
  OMX_STRING cComponentName = "OMX.Action.Image.Decoder";
  omx_base_image_PortType *pInPort,*pOutPort;
  OMX_U32 i;
	pHandle = (OMX_COMPONENTTYPE *)hComponent;
	pHandle->pComponentPrivate = calloc(1, sizeof(omx_jpegdec_component_PrivateType));

    if(pHandle->pComponentPrivate==NULL)  {
      return OMX_ErrorInsufficientResources;
    }
 
  
  omx_jpegdec_component_Private = (omx_jpegdec_component_PrivateType *)pHandle->pComponentPrivate;
  omx_jpegdec_component_Private->ports = NULL;

  /** we could create our own port structures here
    * fixme maybe the base class could use a "port factory" function pointer?  
    */
  err = omx_base_filter_Constructor(pHandle, cComponentName);
 	if (err != OMX_ErrorNone) {
	  return err;
  }

  /** Domain specific section for the ports. */  
  /** first we set the parameter common to both formats
    * parameters related to input port which does not depend upon input image format
    */
  omx_jpegdec_component_Private->sPortTypesParam[OMX_PortDomainImage].nStartPortNumber = 0;
  omx_jpegdec_component_Private->sPortTypesParam[OMX_PortDomainImage].nPorts = 2;

  /** Allocate Ports and call port constructor. */  
  if (omx_jpegdec_component_Private->sPortTypesParam[OMX_PortDomainImage].nPorts && !omx_jpegdec_component_Private->ports) {
    omx_jpegdec_component_Private->ports = calloc(omx_jpegdec_component_Private->sPortTypesParam[OMX_PortDomainImage].nPorts, sizeof(omx_base_PortType *));
    if (!omx_jpegdec_component_Private->ports) {
      return OMX_ErrorInsufficientResources;
    }
    for (i=0; i < omx_jpegdec_component_Private->sPortTypesParam[OMX_PortDomainImage].nPorts; i++) {
      omx_jpegdec_component_Private->ports[i] = calloc(1, sizeof(omx_base_image_PortType));
      if (!omx_jpegdec_component_Private->ports[i]) {
        return OMX_ErrorInsufficientResources;
      }
    }
  }

  err = base_image_port_Constructor(pHandle, &omx_jpegdec_component_Private->ports[0], 0, OMX_TRUE);
  if (err != OMX_ErrorNone) 
  {
  	return err;
  }
  err = base_image_port_Constructor(pHandle, &omx_jpegdec_component_Private->ports[1], 1, OMX_FALSE);
	if (err != OMX_ErrorNone) 
  	{
  		return err;
  	}

    pInPort = (omx_base_image_PortType *) omx_jpegdec_component_Private->ports[OMX_BASE_FILTER_INPUTPORT_INDEX];
    pInPort->sPortParam.nBufferSize = IN_BUFFER_SIZE;
    pInPort->sPortParam.nBufferCountActual = 1;
  /** parameters related to output port */
    pOutPort = (omx_base_image_PortType *) omx_jpegdec_component_Private->ports[OMX_BASE_FILTER_OUTPUTPORT_INDEX];
    pOutPort->sPortParam.nBufferCountActual = 1;
    pOutPort->sPortParam.nBufferSize = OUT_BUFFER_SIZE;

  /** initialise the semaphore to be used for mad decoder access synchronization */
  if(!omx_jpegdec_component_Private->jpegdecSyncSem) {
    omx_jpegdec_component_Private->jpegdecSyncSem = calloc(1,sizeof(tsem_t));
    if(omx_jpegdec_component_Private->jpegdecSyncSem == NULL) {
      return OMX_ErrorInsufficientResources;
    }
    tsem_init(omx_jpegdec_component_Private->jpegdecSyncSem, 0);
  }

  if(!omx_jpegdec_component_Private->jpegdecSyncSem1) {
    omx_jpegdec_component_Private->jpegdecSyncSem1 = calloc(1,sizeof(tsem_t));
    if(omx_jpegdec_component_Private->jpegdecSyncSem1 == NULL) {
      return OMX_ErrorInsufficientResources;
    }
    tsem_init(omx_jpegdec_component_Private->jpegdecSyncSem1, 0);
  }

  /** general configuration irrespective of any image formats
    *  setting values of other fields of omx_jpegdec_component_Private structure  
    */ 
  omx_jpegdec_component_Private->jpegdecReady = OMX_FALSE;
  omx_jpegdec_component_Private->hMarkTargetComponent = NULL;
  omx_jpegdec_component_Private->nFlags = 0x0;
  omx_jpegdec_component_Private->BufferMgmtCallback = omx_jpegdec_component_BufferMgmtCallback;
//  omx_jpegdec_component_Private->BufferMgmtFunction = omx_jpegdec_component_BufferMgmtFunction;
  omx_jpegdec_component_Private->messageHandler = omx_jpegdec_decoder_MessageHandler;
  omx_jpegdec_component_Private->destructor = omx_jpegdec_component_Destructor;
//  pHandle->SetParameter = omx_jpegdec_component_SetParameter;
//  pHandle->GetParameter = omx_jpegdec_component_GetParameter;

  strcpy(std_string, "jpg");
  err = IMGDEC_GetImagePlugin(omx_jpegdec_component_Private, std_string);
//  nojpegdecInstance++;

//  if(nojpegdecInstance>MAX_COMPONENT_JPEGDEC)
//    return OMX_ErrorInsufficientResources;

  return err;
	
}
int main(int argc, char** argv) {
  OMX_ERRORTYPE err = OMX_ErrorNone;
  OMX_BOOL bOmxInitialized = OMX_FALSE;
  OMX_PARAM_PORTDEFINITIONTYPE sOmxPortDefinition;
  OMX_CONFIG_BOOLEANTYPE sOmxCapturing;
  OMX_CONFIG_BOOLEANTYPE sOmxAutoPause;
  OMX_STATETYPE sOmxState;
  OMX_U32 nBufferCount;
  OMX_U32 nBufferSize;
  OMX_U32 nPortIndex;
  OMX_U32 i;
  unsigned int nPreviewTime = 5;/* By default, running for 5 sec for preview */
  unsigned int nCaptureTime = 5;/* By default, running for 5 sec for video capture */
  char *cCaptureFileName = g_DefaultCaptureFileName;
  char *cThumbnailFileName = g_DefaultThumbnailFileName;
  OMX_BOOL bCameraStillImageMode = OMX_FALSE; /* By default, the camera is running in video capture mode */
  OMX_BOOL bCameraAutoPause = OMX_FALSE; /* By default, the camera is not running in autopause mode */
  unsigned int nMaxRunCount = 1;/* By default, running once */
  unsigned int nRunCount = 0;

  /* Parse arguments */
  for ( i = 1; i < argc && argv[i][0] == '-'; i++) {
    switch (argv[i][1]) {
      case 'i':
        bCameraStillImageMode = OMX_TRUE;
        break;

      case 'p':
        bCameraAutoPause = OMX_TRUE;
        break;

      case 't':
        i++;
        if (i>=argc ||argv[i][0] == '-') {
          DEBUG(DEB_LEV_ERR, "preview_time expected!\n");
          display_help(argv[0]);
          exit(-1);
        }
        nPreviewTime = (unsigned int)atoi(argv[i]);
        break;

      case 's':
        i++;
        if (i>=argc ||argv[i][0] == '-') {
          DEBUG(DEB_LEV_ERR, "capture_time expected!\n");
          display_help(argv[0]);
          exit(-1);
        }
        nCaptureTime = (unsigned int)atoi(argv[i]);
        break;

      case 'c':
        i++;
        if (i>=argc ||argv[i][0] == '-') {
          DEBUG(DEB_LEV_ERR, "capture_file expected!\n");
          display_help(argv[0]);
          exit(-1);
        }
        cCaptureFileName = argv[i];
        break;

      case 'm':
        i++;
        if (i>=argc ||argv[i][0] == '-') {
          DEBUG(DEB_LEV_ERR, "thumbnail_file expected!\n");
          display_help(argv[0]);
          exit(-1);
        }
        cThumbnailFileName = argv[i];
        break;

      case 'n':
        i++;
        if (i>=argc ||argv[i][0] == '-') {
          DEBUG(DEB_LEV_ERR, "run_count expected!\n");
          display_help(argv[0]);
          exit(-1);
        }
        nMaxRunCount = (unsigned int)atoi(argv[i]);
        break;

      case 'h':
        display_help(argv[0]);
        exit(0);
        break;

      default:
        DEBUG(DEB_LEV_ERR, "Unrecognized option -%c!\n", argv[i][1]);
        display_help(argv[0]);
        exit(-1);
      }
   }


  /* Init the Omx core */
  DEBUG(DEB_LEV_SIMPLE_SEQ, "Init the OMX core\n");
  if ((err = OMX_Init()) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "The OpenMAX core can not be initialized. Exiting...\n");
    goto EXIT;
  }
  bOmxInitialized =  OMX_TRUE;

  /* Initialize application private data */
  appPriv = malloc(sizeof(appPrivateType));
  if (appPriv == NULL) {
    DEBUG(DEB_LEV_ERR, "Allocate app private data failed!Exiting...\n");
    err = OMX_ErrorInsufficientResources;
    goto EXIT;
  }
  memset(appPriv, 0, sizeof(appPrivateType));

  memset(&sCameraPortBufferList, 0, NUM_CAMERAPORTS*sizeof(OMX_PORTBUFFERCTXT));

  /* Open output file for camera capture and thumbnail port */
  fCapture=fopen(cCaptureFileName, "wb");
  fThumbnail=fopen(cThumbnailFileName, "wb");


  /* Getting camera component handle */
  if ((err = OMX_GetHandle(&appPriv->camerahandle, "OMX.st.v4l.camera_source", appPriv, &camera_source_callbacks)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Getting camera component handle failed!Exiting...\n");
    goto EXIT;
  }

  /* Getting fbsink component handle */
  if ((err = OMX_GetHandle(&appPriv->colorconvhandle, "OMX.st.video_colorconv.ffmpeg", appPriv, &colorconv_callbacks)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Getting color conv component handle failed!Exiting...\n");
    goto EXIT;
  }

  /* Getting fbsink component handle */
  if ((err = OMX_GetHandle(&appPriv->fbsinkhandle, "OMX.st.fbdev.fbdev_sink", appPriv, &fbsink_callbacks)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Getting fbsink component handle failed!Exiting...\n");
    goto EXIT;
  }

  /* Setting parameters for camera component */
  if ((err = setCameraParameters(bCameraStillImageMode)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Set camera parameters failed! Use default settings...\n");
    /* Do not exit! */
  }

  /* Setting parameters for color converter component */
  if ((err = setColorConvParameters()) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Set fbsink parameters failed! Use default settings...\n");
    /* Do not exit! */
  }


  /* Setting parameters for fbsink component */
  if ((err = setFbsinkParameters()) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Set fbsink parameters failed! Use default settings...\n");
    /* Do not exit! */
  }

  /* Allocate and init semaphores */
  appPriv->cameraSourceEventSem = malloc(sizeof(tsem_t));
  if (appPriv->cameraSourceEventSem == NULL) {
    DEBUG(DEB_LEV_ERR, "Allocate camera event semaphore failed!Exiting...\n");
    err = OMX_ErrorInsufficientResources;
    goto EXIT;
  }
  tsem_init(appPriv->cameraSourceEventSem, 0);

  appPriv->fbsinkEventSem = malloc(sizeof(tsem_t));
  if (appPriv->fbsinkEventSem == NULL) {
    DEBUG(DEB_LEV_ERR, "Allocate fbsink event semaphore failed!Exiting...\n");
    err = OMX_ErrorInsufficientResources;
    goto EXIT;
  }
  tsem_init(appPriv->fbsinkEventSem, 0);

  appPriv->colorconvEventSem = malloc(sizeof(tsem_t));
  if (appPriv->colorconvEventSem == NULL) {
    DEBUG(DEB_LEV_ERR, "Allocate colorconv event semaphore failed!Exiting...\n");
    err = OMX_ErrorInsufficientResources;
    goto EXIT;
  }
  tsem_init(appPriv->colorconvEventSem, 0);

  /* Setup tunnel between camera preview port, color converter and fbsink */
  if ((err = OMX_SetupTunnel(appPriv->camerahandle, OMX_CAMPORT_INDEX_VF, appPriv->colorconvhandle, 0)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Setup tunnel between camera preview port and color converter failed!Exiting...\n");
    goto EXIT;
  }
  if ((err = OMX_SetupTunnel(appPriv->colorconvhandle, 1, appPriv->fbsinkhandle, 0)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Setup tunnel between color conv port and fbsink failed!Exiting...\n");
    goto EXIT;
  }

RUN_AGAIN:

  /* Transition camera component Loaded-->Idle */
  if ((err = OMX_SendCommand(appPriv->camerahandle, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Camera Loaded-->Idle failed!Exiting...\n");
    goto EXIT;
  }

  /* Transition color conv component Loaded-->Idle */
  if ((err = OMX_SendCommand(appPriv->colorconvhandle, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Color Conv Loaded-->Idle failed!Exiting...\n");
    goto EXIT;
  }

  /* Transition fbsink component Loaded-->Idle */
  if ((err = OMX_SendCommand(appPriv->fbsinkhandle, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Fbsink Loaded-->Idle failed!Exiting...\n");
    goto EXIT;
  }

  /* Allocate port buffers for camera component */
  for (nPortIndex = OMX_CAMPORT_INDEX_CP; nPortIndex <= OMX_CAMPORT_INDEX_CP_T; nPortIndex++) {
    setHeader(&sOmxPortDefinition, sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
    sOmxPortDefinition.nPortIndex = nPortIndex;
    if ((err = OMX_GetParameter(appPriv->camerahandle, OMX_IndexParamPortDefinition, &sOmxPortDefinition)) != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR, "OMX_GetParameter for camera on OMX_IndexParamPortDefinition index failed!Exiting...\n");
      goto EXIT;
    }
    nBufferCount = sOmxPortDefinition.nBufferCountActual;
    nBufferSize = sOmxPortDefinition.nBufferSize;
    DEBUG(DEB_LEV_SIMPLE_SEQ, "Camera port[%ld] needs %ld buffers each of which is %ld bytes\n", nPortIndex, nBufferCount, nBufferSize);

    for (i = 0; i < nBufferCount; i++) {
      if ((err = OMX_AllocateBuffer(appPriv->camerahandle, &sCameraPortBufferList[nPortIndex].pBufHeaderList[i], nPortIndex, NULL, nBufferSize)) != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR, "Allocate port buffer for camera failed!Exiting...\n");
        goto EXIT;
      }
      sCameraPortBufferList[nPortIndex].nBufferCountActual++;
    }
  }

  /* Wait camera (Loaded-->Idle) to complete */
  tsem_down(appPriv->cameraSourceEventSem);
  /* Wait fbsink (Loaded-->Idle) to complete */
  tsem_down(appPriv->colorconvEventSem);
  /* Wait fbsink (Loaded-->Idle) to complete */
  tsem_down(appPriv->fbsinkEventSem);



  /* Transition camera component Idle-->Exec */
  if ((err = OMX_SendCommand(appPriv->camerahandle, OMX_CommandStateSet, OMX_StateExecuting, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Camera Idle-->Exec failed!Exiting...\n");
    goto EXIT;
  }

  /* Transition color conv component Idle-->Exec */
  if ((err = OMX_SendCommand(appPriv->colorconvhandle, OMX_CommandStateSet, OMX_StateExecuting, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Colorconv Idle-->Exec failed!Exiting...\n");
    goto EXIT;
  }

  /* Transition fbsink component Idle-->Exec */
  if ((err = OMX_SendCommand(appPriv->fbsinkhandle, OMX_CommandStateSet, OMX_StateExecuting, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Fbsink Idle-->Exec failed!Exiting...\n");
    goto EXIT;
  }

  /* Wait camera (Idle-->Exec) to complete */
  tsem_down(appPriv->cameraSourceEventSem);
  /* Wait color conv (Idle-->Exec) to complete */
  tsem_down(appPriv->colorconvEventSem);
  /* Wait fbsink (Idle-->Exec) to complete */
  tsem_down(appPriv->fbsinkEventSem);


  fprintf(stdout, "Start preview, for %d sec...\n", nPreviewTime);
  sleep(nPreviewTime);

  /* Fill buffers to camera capture port */
  for (i = 0; i < sCameraPortBufferList[OMX_CAMPORT_INDEX_CP].nBufferCountActual; i++) {
    sCameraPortBufferList[OMX_CAMPORT_INDEX_CP].pBufHeaderList[i]->nFilledLen = 0;
    sCameraPortBufferList[OMX_CAMPORT_INDEX_CP].pBufHeaderList[i]->nOffset = 0;
    if ((err = OMX_FillThisBuffer(appPriv->camerahandle, sCameraPortBufferList[OMX_CAMPORT_INDEX_CP].pBufHeaderList[i])) != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR, "Fill buffer to camera capture port failed!Exiting...\n");
      goto EXIT;
    }
    DEBUG(DEB_LEV_SIMPLE_SEQ, "%s: Fill buffer[%ld] (0x%lX) to camera capture port\n", __func__, i, (OMX_U32)sCameraPortBufferList[OMX_CAMPORT_INDEX_CP].pBufHeaderList[i]);
  }

  /* Fill buffers to camera thumbnail port */
  for (i = 0; i < sCameraPortBufferList[OMX_CAMPORT_INDEX_CP_T].nBufferCountActual; i++) {
    sCameraPortBufferList[OMX_CAMPORT_INDEX_CP_T].pBufHeaderList[i]->nFilledLen = 0;
    sCameraPortBufferList[OMX_CAMPORT_INDEX_CP_T].pBufHeaderList[i]->nOffset = 0;
    if ((err = OMX_FillThisBuffer(appPriv->camerahandle, sCameraPortBufferList[OMX_CAMPORT_INDEX_CP_T].pBufHeaderList[i])) != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR, "Fill buffer to camera capture port failed!Exiting...\n");
      goto EXIT;
    }
    DEBUG(DEB_LEV_SIMPLE_SEQ, "%s: Fill buffer[%ld] (0x%lX) to camera capture port\n", __func__, i, (OMX_U32)sCameraPortBufferList[OMX_CAMPORT_INDEX_CP_T].pBufHeaderList[i]);
  }

  /* Set up autopause mode */
  setHeader(&sOmxAutoPause, sizeof(OMX_CONFIG_BOOLEANTYPE));
  sOmxAutoPause.bEnabled = bCameraAutoPause;
  if ((err = OMX_SetConfig(appPriv->camerahandle, OMX_IndexAutoPauseAfterCapture, &sOmxAutoPause)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Set autopause mode failed!Use default settings...\n");
    /* Do not exit */
  }

  /*  Start capturing */
  setHeader(&sOmxCapturing, sizeof(OMX_CONFIG_BOOLEANTYPE));
  sOmxCapturing.bEnabled = OMX_TRUE;
  if ((err = OMX_SetConfig(appPriv->camerahandle, OMX_IndexConfigCapturing, &sOmxCapturing)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Start capturing failed!Exiting...\n");
    goto EXIT;
  }

  fprintf(stdout, "Start capturing, for %d sec...\n", nCaptureTime);
  sleep(nCaptureTime);

  /*  Stop capturing */
  if (!bCameraStillImageMode) {
    setHeader(&sOmxCapturing, sizeof(OMX_CONFIG_BOOLEANTYPE));
    sOmxCapturing.bEnabled = OMX_FALSE;
    if ((err = OMX_SetConfig(appPriv->camerahandle, OMX_IndexConfigCapturing, &sOmxCapturing)) != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR, "Stop capturing failed!Exiting...\n");
      goto EXIT;
    }
    fprintf(stdout, "Stop capturing...\n");
  }

  /* If in autopause mode, stay for a while before exit */
  if (bCameraAutoPause) {
    fprintf(stdout, "Now the camera is in autopause mode, wait for %d sec before out of this mode...\n", 5);
    sleep(5);
    /* Stop autopause mode */
    if ((err = OMX_GetState(appPriv->camerahandle,&sOmxState)) != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR, "Get camera state failed!Exiting...\n");
      goto EXIT;
    }
    if (sOmxState == OMX_StatePause) {
      if ((err = OMX_SendCommand(appPriv->camerahandle, OMX_CommandStateSet,
                                                      OMX_StateExecuting, 0 )) != OMX_ErrorNone ) {
        DEBUG(DEB_LEV_ERR, "Pause-->Exec failed!Exiting...\n");
        goto EXIT;
      }
      /* Wait camera (Pause-->Exec) to complete */
      tsem_down(appPriv->cameraSourceEventSem);
      fprintf(stdout, "Now the camera is out of autopause mode, wait for %d sec before exit...\n", 5);
      sleep(5);
    }
    else {
      DEBUG(DEB_LEV_ERR, "The camera is not in Pause state in autopause mode, ignore...\n");
    }
  }

  /* Transition camera component Exec-->Idle */
  if ((err = OMX_SendCommand(appPriv->camerahandle, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Camera Exec-->Idle failed!Exiting...\n");
    goto EXIT;
  }

  /* Transition colorconv component Exec-->Idle */
  if ((err = OMX_SendCommand(appPriv->colorconvhandle, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Color conv Exec-->Idle failed!Exiting...\n");
    goto EXIT;
  }

  /* Transition fbsink component Exec-->Idle */
  if ((err = OMX_SendCommand(appPriv->fbsinkhandle, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Fbsink Exec-->Idle failed!Exiting...\n");
    goto EXIT;
  }

  /* Wait camera (Exec-->Idle) to complete */
  tsem_down(appPriv->cameraSourceEventSem);
  /* Wait color conv (Exec-->Idle) to complete */
  tsem_down(appPriv->colorconvEventSem);
  /* Wait fbsink (Exec-->Idle) to complete */
  tsem_down(appPriv->fbsinkEventSem);


  /* Transition camera component Idle-->Exec */
  if ((err = OMX_SendCommand(appPriv->camerahandle, OMX_CommandStateSet, OMX_StateExecuting, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Camera Idle-->Exec failed!Exiting...\n");
    goto EXIT;
  }

  /* Transition color conv component Idle-->Exec */
  if ((err = OMX_SendCommand(appPriv->colorconvhandle, OMX_CommandStateSet, OMX_StateExecuting, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Colorconv Idle-->Exec failed!Exiting...\n");
    goto EXIT;
  }

  /* Transition fbsink component Idle-->Exec */
  if ((err = OMX_SendCommand(appPriv->fbsinkhandle, OMX_CommandStateSet, OMX_StateExecuting, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Fbsink Idle-->Exec failed!Exiting...\n");
    goto EXIT;
  }

  /* Wait camera (Idle-->Exec) to complete */
  tsem_down(appPriv->cameraSourceEventSem);
  /* Wait color conv (Exec-->Idle) to complete */
  tsem_down(appPriv->colorconvEventSem);
  /* Wait fbsink (Idle-->Exec) to complete */
  tsem_down(appPriv->fbsinkEventSem);

  fprintf(stdout, "Continue to preview, for %d sec...\n", nPreviewTime);
  sleep(nPreviewTime);

  /* Transition camera component Exec-->Idle */
  if ((err = OMX_SendCommand(appPriv->camerahandle, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Camera Exec-->Idle failed!Exiting...\n");
    goto EXIT;
  }

  /* Transition color conv component Exec-->Idle */
  if ((err = OMX_SendCommand(appPriv->colorconvhandle, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Color conv Exec-->Idle failed!Exiting...\n");
    goto EXIT;
  }

  /* Transition fbsink component Exec-->Idle */
  if ((err = OMX_SendCommand(appPriv->fbsinkhandle, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Fbsink Exec-->Idle failed!Exiting...\n");
    goto EXIT;
  }


  /* Wait camera (Exec-->Idle) to complete */
  tsem_down(appPriv->cameraSourceEventSem);
  /* Wait color conv (Exec-->Idle) to complete */
  tsem_down(appPriv->colorconvEventSem);
  /* Wait fbsink (Exec-->Idle) to complete */
  tsem_down(appPriv->fbsinkEventSem);


  /* Transition camera component Idle-->Loaded */
  if ((err = OMX_SendCommand(appPriv->camerahandle, OMX_CommandStateSet, OMX_StateLoaded, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Camera Idle-->Loaded failed!Exiting...\n");
    goto EXIT;
  }

  /* Transition color conv component Idle-->Loaded */
  if ((err = OMX_SendCommand(appPriv->colorconvhandle, OMX_CommandStateSet, OMX_StateLoaded, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Color conv Exec-->Idle failed!Exiting...\n");
    goto EXIT;
  }

  /* Transition fbsink component Idle-->Loaded */
  if ((err = OMX_SendCommand(appPriv->fbsinkhandle, OMX_CommandStateSet, OMX_StateLoaded, NULL)) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Fbsink Idle-->Loaded failed!Exiting...\n");
    goto EXIT;
  }

  /* Free bufers for each non-tunneled port of camera component */
  for (nPortIndex = OMX_CAMPORT_INDEX_CP; nPortIndex <= OMX_CAMPORT_INDEX_CP_T; nPortIndex++) {
    for (i = 0; i < sCameraPortBufferList[nPortIndex].nBufferCountActual; i++) {
      if (sCameraPortBufferList[nPortIndex].pBufHeaderList[i] != NULL) {
        OMX_FreeBuffer(appPriv->camerahandle, nPortIndex, sCameraPortBufferList[nPortIndex].pBufHeaderList[i]);
      }
    }
    sCameraPortBufferList[nPortIndex].nBufferCountActual = 0;
  }

  /* Wait camera (Idle-->Loaded) to complete */
  tsem_down(appPriv->cameraSourceEventSem);
  /* Wait color conv (Exec-->Idle) to complete */
  tsem_down(appPriv->colorconvEventSem);
  /* Wait fbsink (Idle-->Loaded) to complete */
  tsem_down(appPriv->fbsinkEventSem);

  nRunCount++;
  if (nRunCount < nMaxRunCount) {
    goto RUN_AGAIN;
  }

  fprintf(stdout, "The captured videos are saved in file \"%s\"\n", cCaptureFileName);
  fprintf(stdout, "The thumbnail image is saved in file \"%s\"\n", cThumbnailFileName);

EXIT:
  if (fCapture != NULL) {
    fclose(fCapture);
  }
  if (fThumbnail != NULL) {
    fclose(fThumbnail);
  }

  /* Free app private data */
  if (appPriv != NULL) {
    /* Free semaphores */
    if (appPriv->cameraSourceEventSem != NULL) {
      tsem_deinit(appPriv->cameraSourceEventSem);
      free(appPriv->cameraSourceEventSem);
    }

    if (appPriv->colorconvEventSem != NULL) {
      tsem_deinit(appPriv->colorconvEventSem);
      free(appPriv->colorconvEventSem);
    }

    if (appPriv->fbsinkEventSem != NULL) {
      tsem_deinit(appPriv->fbsinkEventSem);
      free(appPriv->fbsinkEventSem);
    }

    /* Free camera component handle */
    if (appPriv->camerahandle != NULL) {
      OMX_FreeHandle(appPriv->camerahandle);
    }
    /* Free Color conv component handle */
    if (appPriv->colorconvhandle != NULL) {
      OMX_FreeHandle(appPriv->colorconvhandle);
    }

    /* Free fbsink component handle */
    if (appPriv->fbsinkhandle != NULL) {
      OMX_FreeHandle(appPriv->fbsinkhandle);
    }

    free(appPriv);
  }

  /* Deinit the Omx core */
  if (bOmxInitialized) {
    OMX_Deinit();
  }

  return (int) err;
}
void start(void) 
{
  tsem_init(&initSem,1);
  return;
}
/** The Constructor
 */
OMX_ERRORTYPE omx_clocksrc_component_Constructor(OMX_COMPONENTTYPE *openmaxStandComp,OMX_STRING cComponentName) {
  int                                 omxErr;
  omx_clocksrc_component_PrivateType* omx_clocksrc_component_Private;
  OMX_U32 i;

	RM_RegisterComponent(CLOCK_COMP_NAME, MAX_CLOCK_COMPONENTS);

  if (!openmaxStandComp->pComponentPrivate) {
    openmaxStandComp->pComponentPrivate = calloc(1, sizeof(omx_clocksrc_component_PrivateType));
    if(openmaxStandComp->pComponentPrivate==NULL) {
      return OMX_ErrorInsufficientResources;
    }
  }

  omx_clocksrc_component_Private = openmaxStandComp->pComponentPrivate;
  omx_clocksrc_component_Private->ports = NULL;

  omxErr = omx_base_source_Constructor(openmaxStandComp,cComponentName);
  if (omxErr != OMX_ErrorNone) {
    return OMX_ErrorInsufficientResources;
  }

  omx_clocksrc_component_Private->sPortTypesParam[OMX_PortDomainOther].nStartPortNumber = 0;
  omx_clocksrc_component_Private->sPortTypesParam[OMX_PortDomainOther].nPorts = 3;

  /** Allocate Ports and call port constructor. */
  if (omx_clocksrc_component_Private->sPortTypesParam[OMX_PortDomainOther].nPorts && !omx_clocksrc_component_Private->ports) {
    omx_clocksrc_component_Private->ports = calloc(omx_clocksrc_component_Private->sPortTypesParam[OMX_PortDomainOther].nPorts, sizeof(omx_base_PortType *));
    if (!omx_clocksrc_component_Private->ports) {
      return OMX_ErrorInsufficientResources;
    }
    for (i=0; i < omx_clocksrc_component_Private->sPortTypesParam[OMX_PortDomainOther].nPorts; i++) {
      omx_clocksrc_component_Private->ports[i] = calloc(1, sizeof(omx_base_clock_PortType));
      if (!omx_clocksrc_component_Private->ports[i]) {
        return OMX_ErrorInsufficientResources;
      }
      base_clock_port_Constructor(openmaxStandComp, &omx_clocksrc_component_Private->ports[i], i, OMX_FALSE);
      omx_clocksrc_component_Private->ports[i]->FlushProcessingBuffers = clocksrc_port_FlushProcessingBuffers;
    }
  }


  /* initializing the OMX_TIME_CONFIG_CLOCKSTATETYPE */
  setHeader(&omx_clocksrc_component_Private->sClockState, sizeof(OMX_TIME_CONFIG_CLOCKSTATETYPE));
  omx_clocksrc_component_Private->sClockState.eState     = OMX_TIME_ClockStateStopped;
  omx_clocksrc_component_Private->sClockState.nStartTime = 0;
  omx_clocksrc_component_Private->sClockState.nOffset    = 0;
  omx_clocksrc_component_Private->sClockState.nWaitMask  = 0xFF;

  setHeader(&omx_clocksrc_component_Private->sMinStartTime, sizeof(OMX_TIME_CONFIG_TIMESTAMPTYPE));
  omx_clocksrc_component_Private->sMinStartTime.nTimestamp = 0;
  omx_clocksrc_component_Private->sMinStartTime.nPortIndex = 0;

  setHeader(&omx_clocksrc_component_Private->sConfigScale, sizeof(OMX_TIME_CONFIG_SCALETYPE));
  omx_clocksrc_component_Private->sConfigScale.xScale = 1<<16;  /* normal play mode */

  setHeader(&omx_clocksrc_component_Private->sRefClock, sizeof(OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE));
  omx_clocksrc_component_Private->sRefClock.eClock = OMX_TIME_RefClockNone;
  omx_clocksrc_component_Private->eUpdateType = OMX_TIME_UpdateMax;

  if(!omx_clocksrc_component_Private->clockEventSem) {
    omx_clocksrc_component_Private->clockEventSem = calloc(1,sizeof(tsem_t));
    tsem_init(omx_clocksrc_component_Private->clockEventSem, 0);
  }

  if(!omx_clocksrc_component_Private->clockEventCompleteSem) {
    omx_clocksrc_component_Private->clockEventCompleteSem = calloc(1,sizeof(tsem_t));
    tsem_init(omx_clocksrc_component_Private->clockEventCompleteSem, 0);
  }

  omx_clocksrc_component_Private->BufferMgmtCallback = omx_clocksrc_component_BufferMgmtCallback;
  omx_clocksrc_component_Private->destructor = omx_clocksrc_component_Destructor;
  omx_clocksrc_component_Private->BufferMgmtFunction = omx_clocksrc_BufferMgmtFunction;

  openmaxStandComp->SetParameter  = omx_clocksrc_component_SetParameter;
  openmaxStandComp->GetParameter  = omx_clocksrc_component_GetParameter;

  openmaxStandComp->SetConfig  = omx_clocksrc_component_SetConfig;
  openmaxStandComp->GetConfig  = omx_clocksrc_component_GetConfig;
  openmaxStandComp->SendCommand = omx_clocksrc_component_SendCommand;

  return OMX_ErrorNone;
}
Beispiel #15
0
int useBufTest()
{
    OMX_ERRORTYPE err = OMX_ErrorNone;
    OMX_BOOL bOmxInitialized = OMX_FALSE;
    OMX_PARAM_PORTDEFINITIONTYPE sOmxPortDefinition;
    OMX_CONFIG_BOOLEANTYPE sOmxCapturing;
    OMX_CONFIG_BOOLEANTYPE sOmxAutoPause;
    OMX_STATETYPE sOmxState;
    OMX_U32 nBufferCount;
    OMX_U32 nBufferSize;
    OMX_U32 nPortIndex;
    OMX_U32 i;
    unsigned int nPreviewTime = 5;/* By default, running for 5 sec for preview */
    unsigned int nCaptureTime = 5;/* By default, running for 5 sec for video capture */
    OMX_BOOL bCameraStillImageMode = OMX_FALSE; /* By default, the camera is running in video capture mode */
    OMX_BOOL bCameraAutoPause = OMX_FALSE; /* By default, the camera is not running in autopause mode */
    unsigned int nMaxRunCount = 1;/* By default, running once */
    unsigned int nRunCount = 0;
    OMX_U8 *buf = NULL;
    

    surface_display_main_init(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT);
    
    /* Init the Omx core */
    DEBUG(DEB_LEV_SIMPLE_SEQ, "Init the OMX core\n");
    if ((err = OMX_Init()) != OMX_ErrorNone)
    {
        DEBUG(DEB_LEV_ERR,
                "The OpenMAX core can not be initialized. Exiting...\n");
        goto EXIT;
    }
    bOmxInitialized = OMX_TRUE;
    
    /* Initialize application private data */
    appPriv = malloc(sizeof(appPrivateType));
    if (appPriv == NULL)
    {
        DEBUG(DEB_LEV_ERR, "Allocate app private data failed!Exiting...\n");
        err = OMX_ErrorInsufficientResources;
        goto EXIT;
    }
    memset(appPriv, 0, sizeof(appPrivateType));
    
    memset(&sCameraPortBufferList, 0,
            NUM_CAMERAPORTS * sizeof(OMX_PORTBUFFERCTXT));
    
    /* Getting camera component handle */
    if ((err = OMX_GetHandle(&appPriv->camerahandle,
            "OMX.Action.Camera.Yuv", appPriv, &camera_source_callbacks))
            != OMX_ErrorNone)
    {
        DEBUG(DEB_LEV_ERR,
                "Getting camera component handle failed!Exiting...\n");
        goto EXIT;
    }

    /* Setting parameters for camera component */
    if ((err = setCameraParameters(bCameraStillImageMode)) != OMX_ErrorNone)
    {
        DEBUG(DEB_LEV_ERR,
                "Set camera parameters failed! Use default settings...\n");
        /* Do not exit! */
    }

    /* Allocate and init semaphores */
    appPriv->cameraSourceEventSem = malloc(sizeof(tsem_t));
    if (appPriv->cameraSourceEventSem == NULL)
    {
        DEBUG(DEB_LEV_ERR,
                "Allocate camera event semaphore failed!Exiting...\n");
        err = OMX_ErrorInsufficientResources;
        goto EXIT;
    }
    tsem_init(appPriv->cameraSourceEventSem, 0);
    
    RUN_AGAIN:

    for (nPortIndex = OMX_CAMPORT_INDEX_VF; nPortIndex <= OMX_CAMPORT_INDEX_CP; nPortIndex++)
    {
        
        if ((err = OMX_SendCommand(appPriv->camerahandle,
                OMX_CommandPortEnable, nPortIndex, NULL)) != OMX_ErrorNone)
        {
            DEBUG(DEB_LEV_ERR, "Camera Idle-->Exec failed!Exiting...\n");
            goto EXIT;
        }
        tsem_down(appPriv->cameraSourceEventSem);
    }
    /* Transition camera component Loaded-->Idle */
    if ((err = OMX_SendCommand(appPriv->camerahandle, OMX_CommandStateSet,
            OMX_StateIdle, NULL)) != OMX_ErrorNone)
    {
        DEBUG(DEB_LEV_ERR, "Camera Loaded-->Idle failed!Exiting...\n");
        goto EXIT;
    }

    /* Allocate port buffers for camera component */
    for (nPortIndex = OMX_CAMPORT_INDEX_VF; nPortIndex <= OMX_CAMPORT_INDEX_CP; nPortIndex++)
    {
        
        setHeader(&sOmxPortDefinition, sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
        sOmxPortDefinition.nPortIndex = nPortIndex;
        if ((err = OMX_GetParameter(appPriv->camerahandle,
                OMX_IndexParamPortDefinition, &sOmxPortDefinition))
                != OMX_ErrorNone)
        {
            DEBUG(
                    DEB_LEV_ERR,
                    "OMX_GetParameter for camera on OMX_IndexParamPortDefinition index failed!Exiting...\n");
            goto EXIT;
        }
        nBufferCount = sOmxPortDefinition.nBufferCountActual;
        nBufferSize = sOmxPortDefinition.nBufferSize;
        DEBUG(
                DEB_LEV_SIMPLE_SEQ,
                "Camera port[%ld] needs %ld buffers each of which is %ld bytes\n",
                nPortIndex, nBufferCount, nBufferSize);
        
        for (i = 0; i < nBufferCount; i++)
        {
            buf = (OMX_U8 *)malloc(nBufferSize);
            if(buf == NULL){
                DEBUG(DEB_LEV_ERR,
                        "Allocate port buffer for camera failed!Exiting...\n");
                goto EXIT;
            }
            
            if ((err = OMX_UseBuffer(appPriv->camerahandle,
                    &sCameraPortBufferList[nPortIndex].pBufHeaderList[i],
                    nPortIndex, NULL, nBufferSize, buf)) != OMX_ErrorNone)
            {
                DEBUG(DEB_LEV_ERR,
                        "Allocate port buffer for camera failed!Exiting...\n");
                goto EXIT;
            }
            sCameraPortBufferList[nPortIndex].nBufferCountActual++;
        }
    }

    /* Wait camera (Loaded-->Idle) to complete */
    tsem_down(appPriv->cameraSourceEventSem);
    
    /* Transition camera component Idle-->Exec */
    if ((err = OMX_SendCommand(appPriv->camerahandle, OMX_CommandStateSet,
            OMX_StateExecuting, NULL)) != OMX_ErrorNone)
    {
        DEBUG(DEB_LEV_ERR, "Camera Idle-->Exec failed!Exiting...\n");
        goto EXIT;
    }

    /* Wait camera (Idle-->Exec) to complete */
    tsem_down(appPriv->cameraSourceEventSem);
    
    /* Fill buffers to camera preview port */
    for (i = 0; i
            < sCameraPortBufferList[OMX_CAMPORT_INDEX_VF].nBufferCountActual; i++)
    {
        sCameraPortBufferList[OMX_CAMPORT_INDEX_VF].pBufHeaderList[i]->nFilledLen
                = 0;
        sCameraPortBufferList[OMX_CAMPORT_INDEX_VF].pBufHeaderList[i]->nOffset
                = 0;
        if ((err = OMX_FillThisBuffer(appPriv->camerahandle,
                sCameraPortBufferList[OMX_CAMPORT_INDEX_VF].pBufHeaderList[i]))
                != OMX_ErrorNone)
        {
            DEBUG(DEB_LEV_ERR,
                    "Fill buffer to camera capture port failed!Exiting...\n");
            goto EXIT;
        }
        DEBUG(
                DEB_LEV_SIMPLE_SEQ,
                "%s: Fill buffer[%ld] (0x%lX) to camera capture port\n",
                __func__,
                i,
                (OMX_U32) sCameraPortBufferList[OMX_CAMPORT_INDEX_VF].pBufHeaderList[i]);
    }

    /* Fill buffers to camera capture port */
    for (i = 0; i
            < sCameraPortBufferList[OMX_CAMPORT_INDEX_CP].nBufferCountActual; i++)
    {
        sCameraPortBufferList[OMX_CAMPORT_INDEX_CP].pBufHeaderList[i]->nFilledLen
                = 0;
        sCameraPortBufferList[OMX_CAMPORT_INDEX_CP].pBufHeaderList[i]->nOffset
                = 0;
        if ((err = OMX_FillThisBuffer(appPriv->camerahandle,
                sCameraPortBufferList[OMX_CAMPORT_INDEX_CP].pBufHeaderList[i]))
                != OMX_ErrorNone)
        {
            DEBUG(DEB_LEV_ERR,
                    "Fill buffer to camera capture port failed!Exiting...\n");
            goto EXIT;
        }
        DEBUG(
                DEB_LEV_SIMPLE_SEQ,
                "%s: Fill buffer[%ld] (0x%lX) to camera capture port\n",
                __func__,
                i,
                (OMX_U32) sCameraPortBufferList[OMX_CAMPORT_INDEX_CP].pBufHeaderList[i]);
    }

    fprintf(stdout, "Start preview, for %d sec...\n", nPreviewTime);
    sleep(nPreviewTime);
    
    /* Set up autopause mode */
    setHeader(&sOmxAutoPause, sizeof(OMX_CONFIG_BOOLEANTYPE));
    sOmxAutoPause.bEnabled = bCameraAutoPause;
    if ((err = OMX_SetConfig(appPriv->camerahandle,
            OMX_IndexAutoPauseAfterCapture, &sOmxAutoPause)) != OMX_ErrorNone)
    {
        DEBUG(DEB_LEV_ERR,
                "Set autopause mode failed!Use default settings...\n");
        /* Do not exit */
    }

    /*  Start capturing */
    setHeader(&sOmxCapturing, sizeof(OMX_CONFIG_BOOLEANTYPE));
    sOmxCapturing.bEnabled = OMX_TRUE;
    if ((err = OMX_SetConfig(appPriv->camerahandle, OMX_IndexConfigCapturing,
            &sOmxCapturing)) != OMX_ErrorNone)
    {
        DEBUG(DEB_LEV_ERR, "Start capturing failed!Exiting...\n");
        goto EXIT;
    }

    fprintf(stdout, "Start capturing, for %d sec...\n", nCaptureTime);
    sleep(nCaptureTime);
    
    /*  Stop capturing */
    if (!bCameraStillImageMode)
    {
        setHeader(&sOmxCapturing, sizeof(OMX_CONFIG_BOOLEANTYPE));
        sOmxCapturing.bEnabled = OMX_FALSE;
        if ((err = OMX_SetConfig(appPriv->camerahandle,
                OMX_IndexConfigCapturing, &sOmxCapturing)) != OMX_ErrorNone)
        {
            DEBUG(DEB_LEV_ERR, "Stop capturing failed!Exiting...\n");
            goto EXIT;
        }
        fprintf(stdout, "Stop capturing...\n");
    }

    /* If in autopause mode, stay for a while before exit */
    if (bCameraAutoPause)
    {
        fprintf( stdout,"pause state for capture, sleep(%d)\n",5);
        sleep(5);
        /* Stop autopause mode */
        if ((err = OMX_GetState(appPriv->camerahandle, &sOmxState))
                != OMX_ErrorNone)
        {
            DEBUG(DEB_LEV_ERR, "Get camera state failed!Exiting...\n");
            goto EXIT;
        }
        if (sOmxState == OMX_StatePause)
        {
            if ((err = OMX_SendCommand(appPriv->camerahandle,
                    OMX_CommandStateSet, OMX_StateExecuting, 0))
                    != OMX_ErrorNone)
            {
                DEBUG(DEB_LEV_ERR, "Pause-->Exec failed!Exiting...\n");
                goto EXIT;
            }
            /* Wait camera (Pause-->Exec) to complete */
            tsem_down(appPriv->cameraSourceEventSem);
            fprintf(
                    stdout,
                    "Now the camera is out of autopause mode, wait for %d sec before exit...\n",
                    5);
            sleep(5);
        }
        else
        {
            DEBUG(DEB_LEV_ERR,
                    "The camera is not in Pause state in autopause mode, ignore...\n");
        }
    }

#if 1
    /* Transition camera component Exec-->Idle */
    if ((err = OMX_SendCommand(appPriv->camerahandle, OMX_CommandStateSet,
            OMX_StateIdle, NULL)) != OMX_ErrorNone)
    {
        DEBUG(DEB_LEV_ERR, "Camera Exec-->Idle failed!Exiting...\n");
        goto EXIT;
    }

    /* Wait camera (Exec-->Idle) to complete */
    tsem_down(appPriv->cameraSourceEventSem);
    
    /* Transition camera component Idle-->Exec */
    if ((err = OMX_SendCommand(appPriv->camerahandle, OMX_CommandStateSet,
            OMX_StateExecuting, NULL)) != OMX_ErrorNone)
    {
        DEBUG(DEB_LEV_ERR, "Camera Idle-->Exec failed!Exiting...\n");
        goto EXIT;
    }

    /* Wait camera (Idle-->Exec) to complete */
    tsem_down(appPriv->cameraSourceEventSem);
    
    /* Fill buffers to camera preview port */
    for (i = 0; i
            < sCameraPortBufferList[OMX_CAMPORT_INDEX_VF].nBufferCountActual; i++)
    {
        sCameraPortBufferList[OMX_CAMPORT_INDEX_VF].pBufHeaderList[i]->nFilledLen
                = 0;
        sCameraPortBufferList[OMX_CAMPORT_INDEX_VF].pBufHeaderList[i]->nOffset
                = 0;
        if ((err = OMX_FillThisBuffer(appPriv->camerahandle,
                sCameraPortBufferList[OMX_CAMPORT_INDEX_VF].pBufHeaderList[i]))
                != OMX_ErrorNone)
        {
            DEBUG(DEB_LEV_ERR,
                    "Fill buffer to camera capture port failed!Exiting...\n");
            goto EXIT;
        }
        DEBUG(
                DEB_LEV_SIMPLE_SEQ,
                "%s: Fill buffer[%ld] (0x%lX) to camera capture port\n",
                __func__,
                i,
                (OMX_U32) sCameraPortBufferList[OMX_CAMPORT_INDEX_VF].pBufHeaderList[i]);
    }

    /* Fill buffers to camera capture port */
    for (i = 0; i
            < sCameraPortBufferList[OMX_CAMPORT_INDEX_CP].nBufferCountActual; i++)
    {
        sCameraPortBufferList[OMX_CAMPORT_INDEX_CP].pBufHeaderList[i]->nFilledLen
                = 0;
        sCameraPortBufferList[OMX_CAMPORT_INDEX_CP].pBufHeaderList[i]->nOffset
                = 0;
        if ((err = OMX_FillThisBuffer(appPriv->camerahandle,
                sCameraPortBufferList[OMX_CAMPORT_INDEX_CP].pBufHeaderList[i]))
                != OMX_ErrorNone)
        {
            DEBUG(DEB_LEV_ERR,
                    "Fill buffer to camera capture port failed!Exiting...\n");
            goto EXIT;
        }
        DEBUG(
                DEB_LEV_SIMPLE_SEQ,
                "%s: Fill buffer[%ld] (0x%lX) to camera capture port\n",
                __func__,
                i,
                (OMX_U32) sCameraPortBufferList[OMX_CAMPORT_INDEX_CP].pBufHeaderList[i]);
    }

    fprintf(stdout, "Continue to preview, for %d sec...\n", nPreviewTime);
    sleep(nPreviewTime);
    
#endif
    /* Transition camera component Exec-->Idle */
    if ((err = OMX_SendCommand(appPriv->camerahandle, OMX_CommandStateSet,
            OMX_StateIdle, NULL)) != OMX_ErrorNone)
    {
        DEBUG(DEB_LEV_ERR, "Camera Exec-->Idle failed!Exiting...\n");
        goto EXIT;
    }

    /* Wait camera (Exec-->Idle) to complete */
    tsem_down(appPriv->cameraSourceEventSem);
    
    /* Transition camera component Idle-->Loaded */
    if ((err = OMX_SendCommand(appPriv->camerahandle, OMX_CommandStateSet,
            OMX_StateLoaded, NULL)) != OMX_ErrorNone)
    {
        DEBUG(DEB_LEV_ERR, "Camera Idle-->Loaded failed!Exiting...\n");
        goto EXIT;
    }

#if 1
    /* Free bufers for each non-tunneled port of camera component */
    for (nPortIndex = OMX_CAMPORT_INDEX_VF; nPortIndex <= OMX_CAMPORT_INDEX_CP; nPortIndex++)
    {
        for (i = 0; i < sCameraPortBufferList[nPortIndex].nBufferCountActual; i++)
        {
            if (sCameraPortBufferList[nPortIndex].pBufHeaderList[i] != NULL)
            {
                buf = sCameraPortBufferList[nPortIndex].pBufHeaderList[i]->pBuffer;
                OMX_FreeBuffer(appPriv->camerahandle, nPortIndex,
                        sCameraPortBufferList[nPortIndex].pBufHeaderList[i]);
                if(buf){
                    free(buf);
                }
                sCameraPortBufferList[nPortIndex].pBufHeaderList[i]=NULL;
            }
        }
        sCameraPortBufferList[nPortIndex].nBufferCountActual = 0;
    }
#endif
    
    /* Wait camera (Idle-->Loaded) to complete */
    tsem_down(appPriv->cameraSourceEventSem);
    
    nRunCount++;
    if (nRunCount < nMaxRunCount)
    {
        goto RUN_AGAIN;
    }

   
    EXIT: 

    for (nPortIndex = OMX_CAMPORT_INDEX_VF; nPortIndex <= OMX_CAMPORT_INDEX_CP; nPortIndex++)
    {
        for (i = 0; i < sCameraPortBufferList[nPortIndex].nBufferCountActual; i++)
        {
            if (sCameraPortBufferList[nPortIndex].pBufHeaderList[i] != NULL)
            {
                buf = sCameraPortBufferList[nPortIndex].pBufHeaderList[i]->pBuffer;
                OMX_FreeBuffer(appPriv->camerahandle, nPortIndex,
                        sCameraPortBufferList[nPortIndex].pBufHeaderList[i]);
                if(buf){
                    free(buf);
                }
                sCameraPortBufferList[nPortIndex].pBufHeaderList[i]=NULL; 
            }
        }
        sCameraPortBufferList[nPortIndex].nBufferCountActual = 0;
    }   

    /* Free app private data */
    if (appPriv != NULL)
    {
        /* Free semaphores */
        if (appPriv->cameraSourceEventSem != NULL)
        {
            tsem_deinit(appPriv->cameraSourceEventSem);
            free(appPriv->cameraSourceEventSem);
        }

        /* Free camera component handle */
        if (appPriv->camerahandle != NULL)
        {
            OMX_FreeHandle(appPriv->camerahandle);
        }
        
        free(appPriv);
    }

    /* Deinit the Omx core */
    if (bOmxInitialized)
    {
        OMX_Deinit();
    }
    
    return (int) err;
}
Beispiel #16
0
long
shvpu_driver_init(shvpu_driver_t **ppDriver)
{
	long ret = 0;
	unsigned long reg_base;
	int zero = 0;

	pthread_mutex_lock(&initMutex);

	/* pass the pointer if the driver was already initialized */
	if (nCodecInstances > 0)
		goto init_already;

	/*** workaround clear VP5_IRQ_ENB and VPU5_IRQ_STA ***/
	reg_base = uio_register_base();
	vpu5_mmio_write(reg_base + VP5_IRQ_ENB, (unsigned long) &zero, 1);
	vpu5_mmio_write(reg_base + VP5_IRQ_STA, (unsigned long) &zero, 1);

	pDriver = (shvpu_driver_t *)calloc(1, sizeof(shvpu_driver_t));
	if (pDriver == NULL) {
		ret = -1;
		goto init_failed;
	}
	memset((void *)pDriver, 0, sizeof(shvpu_driver_t));

	/*** initialize vpu ***/
#if defined(VPU5HA_SERIES)
	pDriver->wbufVpu5.work_size = MCIPH_IP0_WORKAREA_SIZE;
#elif defined(VPU_VERSION_5)
	pDriver->wbufVpu5.work_size = MCIPH_HG_WORKAREA_SIZE;
#endif
	pDriver->wbufVpu5.work_area_addr =
		malloc_aligned(pDriver->wbufVpu5.work_size, 4);
	logd("work_area_addr = %p\n", pDriver->wbufVpu5.work_area_addr);
	if ((pDriver->wbufVpu5.work_area_addr == NULL) ||
	    ((unsigned int)pDriver->wbufVpu5.work_area_addr & 0x03U)) {
		ret = -1;
		goto init_failed;
	}

	pDriver->vpu5Init.vpu_base_address		= uio_register_base();
	pDriver->vpu5Init.vpu_image_endian		= MCIPH_LIT;
	pDriver->vpu5Init.vpu_stream_endian		= MCIPH_LIT;
	pDriver->vpu5Init.vpu_firmware_endian		= MCIPH_LIT;
	pDriver->vpu5Init.vpu_interrupt_enable		= MCIPH_ON;
	pDriver->vpu5Init.vpu_clock_supply_control	= MCIPH_CLK_CTRL;
#ifdef VPU_INTERNAL_TL
	pDriver->vpu5Init.vpu_constrained_mode		= MCIPH_VPU_TL;
#else
	pDriver->vpu5Init.vpu_constrained_mode		= MCIPH_OFF;
#endif
	pDriver->vpu5Init.vpu_address_mode		= MCIPH_ADDR_32BIT;
	pDriver->vpu5Init.vpu_reset_mode		= MCIPH_RESET_SOFT;
#if defined(VPU5HA_SERIES)
	pDriver->vpu5Init.vpu_version			= MCIPH_NA;
	pDriver->vpu5Init.vpu_ext_init			= &(pDriver->ip0Init);

#ifdef DECODER_COMPONENT
#ifdef MPEG4_DECODER
	pDriver->ip0Init.dec_tbl[0] = &mciph_ip0_m4vdec_api_tbl;
	pDriver->ip0Init.dec_tbl[1] = &mciph_ip0_m4vdec_api_tbl;
#endif
	pDriver->ip0Init.dec_tbl[2] = &mciph_ip0_avcdec_api_tbl;
	pDriver->apiTbl.dec_api_tbl 	= &mciph_ip0_dec_api_tbl;
#endif
#ifdef ENCODER_COMPONENT
	pDriver->ip0Init.enc_tbl[2] = &mciph_ip0_avcenc_api_tbl;
	pDriver->apiTbl.enc_api_tbl 	= &mciph_ip0_enc_api_tbl;
#endif

	pDriver->apiTbl.cmn_api_tbl 	= &mciph_ip0_cmn_api_tbl;
#if defined(VPU_VERSION_5HD)
	pDriver->ip0Init.drv_extensions = 0x3;
#endif
#elif defined(VPU_VERSION_5)
	memcpy(&(pDriver->apiTbl), &mciph_hg_api_tbl, sizeof(mciph_hg_api_tbl));
#endif
	logd("----- invoke mciph_vpu5Init() -----\n");
	ret = mciph_vpu5_init(&(pDriver->wbufVpu5),
			      &(pDriver->apiTbl),
			      &(pDriver->vpu5Init),
			      &(pDriver->pDrvInfo));
	logd("----- resume from mciph_vpu5_init() -----\n");

	if (ret != MCIPH_NML_END)
		goto init_failed;

	/* register an interrupt handler */
	tsem_init(&pDriver->uioSem, 0);
	ret = uio_create_int_handle(&pDriver->intrHandler,
				    handle_shvpu5_interrupt,
				    pDriver->pDrvInfo,
				    &pDriver->uioSem, &pDriver->isExit);
	if (ret < 0)
		goto init_failed;

init_already:
	*ppDriver = pDriver;
	nCodecInstances++;
init_failed:
	pthread_mutex_unlock(&initMutex);
	return ret;
}
int main(int argc, char** argv) {
  int argn_dec;
  OMX_ERRORTYPE err;
  OMX_INDEXTYPE eIndexParamFilename;
  int gain=-1;
  OMX_AUDIO_CONFIG_VOLUMETYPE sVolume;
  OMX_TIME_CONFIG_TIMESTAMPTYPE sTimeStamp;
  OMX_PARAM_COMPONENTROLETYPE sComponentRole;
  
  char *stream_dir=NULL;
  DIR *dirp;
	struct dirent *dp;
  int seek=1;

  flagSetupTunnel = 1;
  flagPlaybackOn = 1;
  flagUsingFFMpeg = 1;
  flagIsGain = 0;

  if(argc <= 3) {
    argn_dec = 1;
    while (argn_dec<argc) {
      if (*(argv[argn_dec]) =='-') {
        switch (*(argv[argn_dec]+1)) {
        case 's':
          seek = 0;
          break;
        //case 't':
        //  flagSetupTunnel = 0;
        //  break;
        default:
          display_help();
        }
      } else {
        stream_dir = malloc(strlen(argv[argn_dec]) * sizeof(char) + 1);
        strcpy(stream_dir,argv[argn_dec]);
      }
      argn_dec++;
    }
  } else if(argc > 3) {
    display_help();
  }

  if(stream_dir==NULL) {

    stream_dir = malloc(strlen(getenv("HOME")) * sizeof(char) + 20);
    memset(stream_dir, 0, sizeof(stream_dir));
	  strcat(stream_dir, getenv("HOME"));
	  strcat(stream_dir, "/stream/audio/");
  }

  DEBUG(DEFAULT_MESSAGES, "Directory Name=%s\n",stream_dir);

  /* Populate the registry file */
	dirp = opendir(stream_dir);
	if(dirp == NULL){
    int err = errno;
		DEBUG(DEB_LEV_ERR, "Cannot open directory %s\n", stream_dir);
		return err;
	}

  
  /** initializing appPriv structure */
  appPriv = malloc(sizeof(appPrivateType));
  appPriv->filereaderEventSem = malloc(sizeof(tsem_t));
  appPriv->decoderEventSem = malloc(sizeof(tsem_t));
  appPriv->eofSem = malloc(sizeof(tsem_t));
  if (flagPlaybackOn) {
    appPriv->sinkEventSem = malloc(sizeof(tsem_t));
    tsem_init(appPriv->sinkEventSem, 0);
    appPriv->volumeEventSem = malloc(sizeof(tsem_t));
    tsem_init(appPriv->volumeEventSem, 0);
  }
  tsem_init(appPriv->filereaderEventSem, 0);
  tsem_init(appPriv->decoderEventSem, 0);
  tsem_init(appPriv->eofSem, 0);

  /** initialising openmax */
  err = OMX_Init();
  if (err != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "The OpenMAX core can not be initialized. Exiting...\n");
    exit(1);
  } 

  

  if(flagUsingFFMpeg) {
    DEBUG(DEB_LEV_SIMPLE_SEQ, "Using File Reader\n");
    /** file reader component name -- gethandle*/
    err = OMX_GetHandle(&appPriv->filereaderhandle, FILE_READER, NULL , &filereadercallbacks);
    if(err != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR, "FileReader Component Not Found\n");
      exit(1);
    }  
    err = OMX_GetExtensionIndex(appPriv->filereaderhandle,"OMX.ST.index.param.inputfilename",&eIndexParamFilename);
    if(err != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR,"\n error in get extension index\n");
			exit(1);
    } 
  }

  /** getting the handle of audio decoder */
  err = OMX_GetHandle(&appPriv->audiodechandle, COMPONENT_NAME_BASE, NULL , &audiodeccallbacks);
  if(err != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Audio Decoder Component Not Found\n");
		exit(1);
  } 
  DEBUG(DEFAULT_MESSAGES, "Component %s opened\n", COMPONENT_NAME_BASE);

  if (flagPlaybackOn) {
    err = OMX_GetHandle(&appPriv->audiosinkhandle, SINK_NAME, NULL , &audiosinkcallbacks);
    if(err != OMX_ErrorNone){
      DEBUG(DEB_LEV_ERR, "No sink found. Exiting...\n");
      exit(1);
    }

    DEBUG(DEFAULT_MESSAGES, "Getting Handle for Component %s\n", AUDIO_EFFECT);
    err = OMX_GetHandle(&appPriv->volumehandle, AUDIO_EFFECT, NULL , &volumecallbacks);
    if(err != OMX_ErrorNone){
      DEBUG(DEB_LEV_ERR, "No sink found. Exiting...\n");
      exit(1);
    }

    if((gain >= 0) && (gain <100)) {
      err = OMX_GetConfig(appPriv->volumehandle, OMX_IndexConfigAudioVolume, &sVolume);
      if(err!=OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"Error %08x In OMX_GetConfig 0 \n",err);
      }
      sVolume.sVolume.nValue = gain;
      DEBUG(DEFAULT_MESSAGES, "Setting Gain %d \n", gain);
      err = OMX_SetConfig(appPriv->volumehandle, OMX_IndexConfigAudioVolume, &sVolume);
      if(err!=OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"Error %08x In OMX_SetConfig 0 \n",err);
      }
    }
  }

  if (flagSetupTunnel) {
    DEBUG(DEB_LEV_SIMPLE_SEQ, "Setting up Tunnel\n");
    if(flagUsingFFMpeg) {
      err = OMX_SetupTunnel(appPriv->filereaderhandle, 0, appPriv->audiodechandle, 0);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR, "Set up Tunnel Failed\n");
        exit(1);
      }
    }
    err = OMX_SetupTunnel(appPriv->audiodechandle, 1, appPriv->volumehandle, 0);
    if(err != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR, "Set up Tunnel Failed\n");
      exit(1);
    }
    err = OMX_SetupTunnel(appPriv->volumehandle, 1, appPriv->audiosinkhandle, 0);
    if(err != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR, "Set up Tunnel Failed\n");
      exit(1);
    }
    DEBUG(DEB_LEV_SIMPLE_SEQ, "Set up Tunnel Completed\n");
  }

  if(flagUsingFFMpeg) {
    /** now set the filereader component to idle and executing state */
    OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
  }

  /*Send State Change Idle command to Audio Decoder*/
  DEBUG(DEB_LEV_SIMPLE_SEQ, "Send Command Idle to Audio Dec\n");
  err = OMX_SendCommand(appPriv->audiodechandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
  if (flagPlaybackOn) {
    DEBUG(DEB_LEV_SIMPLE_SEQ, "Send Command Idle to Audio Sink\n");
    err = OMX_SendCommand(appPriv->volumehandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
    err = OMX_SendCommand(appPriv->audiosinkhandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
  }

  if(flagUsingFFMpeg) {
      /*Wait for File reader state change to */
    tsem_down(appPriv->filereaderEventSem);
    DEBUG(DEFAULT_MESSAGES,"File reader idle state \n");
  }

  tsem_down(appPriv->decoderEventSem);
  if (flagPlaybackOn) {
    tsem_down(appPriv->volumeEventSem);
    DEBUG(DEFAULT_MESSAGES,"volume state idle\n");
    tsem_down(appPriv->sinkEventSem);
    DEBUG(DEFAULT_MESSAGES,"audio sink state idle\n");
  }

  if (flagPlaybackOn) {
    err = OMX_SendCommand(appPriv->volumehandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
    if(err != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR,"volume state executing failed\n");
			exit(1);
    }
    DEBUG(DEB_LEV_SIMPLE_SEQ,"waiting for  volume state executing\n");
    tsem_down(appPriv->volumeEventSem);

    DEBUG(DEB_LEV_SIMPLE_SEQ,"sending audio sink state executing\n");
    err = OMX_SendCommand(appPriv->audiosinkhandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
    if(err != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR,"audio sink state executing failed\n");
			exit(1);
    }
    DEBUG(DEB_LEV_SIMPLE_SEQ,"waiting for  audio sink state executing\n");
    tsem_down(appPriv->sinkEventSem);
    DEBUG(DEB_LEV_SIMPLE_SEQ, "audio sink state executing successful\n");
  } 
  
  setHeader(&sComponentRole, sizeof(OMX_PARAM_COMPONENTROLETYPE));
  strcpy((char*)&sComponentRole.cRole[0], MP3_ROLE);

  while((dp = readdir(dirp)) != NULL) {
    int len = strlen(dp->d_name);

		if(len >= 3){
      
      if(strncmp(dp->d_name+len-4, ".mp3", 4) == 0){
        
        if(input_file!=NULL) {
          free(input_file);
          input_file=NULL;
        }

        input_file = malloc(strlen(stream_dir) * sizeof(char) + sizeof(dp->d_name) +1);
        strcpy(input_file,stream_dir);
				strcat(input_file, dp->d_name);

        DEBUG(DEFAULT_MESSAGES, "Input Mp3 File Name=%s\n",input_file);

        flagUsingFFMpeg = 1;

        strcpy((char*)&sComponentRole.cRole[0], MP3_ROLE);

      } else if(strncmp(dp->d_name+len-4, ".ogg", 4) == 0){
        
        if(input_file!=NULL) {
          free(input_file);
          input_file=NULL;
        }

        input_file = malloc(strlen(stream_dir) * sizeof(char) + sizeof(dp->d_name) +1);
        strcpy(input_file,stream_dir);
				strcat(input_file, dp->d_name);

        DEBUG(DEFAULT_MESSAGES, "Input Vorbis File Name=%s\n",input_file);

        flagUsingFFMpeg = 1;

        strcpy((char*)&sComponentRole.cRole[0], VORBIS_ROLE);
                
      } else if(strncmp(dp->d_name+len-4, ".aac", 4) == 0){
        
        if(input_file!=NULL) {
          free(input_file);
          input_file=NULL;
        }

        input_file = malloc(strlen(stream_dir) * sizeof(char) + sizeof(dp->d_name) +1);
        strcpy(input_file,stream_dir);
				strcat(input_file, dp->d_name);

        DEBUG(DEFAULT_MESSAGES, "Input AAC File Name=%s\n",input_file);

        flagUsingFFMpeg = 1;

        strcpy((char*)&sComponentRole.cRole[0], AAC_ROLE);
                
      } else {
        continue;
      }
    } else {
      continue;
    }

    
    /*Reset Global Variables*/
    tsem_reset(appPriv->eofSem);
    bEOS=OMX_FALSE;

    if (flagUsingFFMpeg) {
      DEBUG(DEB_LEV_SIMPLE_SEQ,"Sending Port Disable Command State Idle\n");
      /*Port Disable for filereader is sent from Port Settings Changed event of FileReader*/
      err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandPortDisable, 0, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"file reader port disable failed\n");
			  exit(1);
      }
      err = OMX_SendCommand(appPriv->audiodechandle, OMX_CommandPortDisable, OMX_ALL, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"audio decoder port disable failed\n");
			  exit(1);
      }

      err = OMX_SendCommand(appPriv->volumehandle, OMX_CommandPortDisable, 0, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"audio sink port disable failed\n");
			  exit(1);
      }
      
      DEBUG(DEB_LEV_SIMPLE_SEQ,"Waiting File reader Port Disable event \n");
      /*Wait for File Reader Ports Disable Event*/
      tsem_down(appPriv->filereaderEventSem);
      DEBUG(DEB_LEV_SIMPLE_SEQ,"File reader Port Disable State Idle\n");
      /*Wait for Audio Decoder Ports Disable Event*/
      tsem_down(appPriv->decoderEventSem);
      tsem_down(appPriv->decoderEventSem);

      tsem_down(appPriv->volumeEventSem);

      err = OMX_SendCommand(appPriv->audiodechandle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
      tsem_down(appPriv->decoderEventSem);
    }


    DEBUG(DEB_LEV_SIMPLE_SEQ,"Setting Role\n");

    err = OMX_SetParameter(appPriv->audiodechandle,OMX_IndexParamStandardComponentRole,&sComponentRole);
    if(err != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR,"\n error in input audio format - exiting\n");
      exit(1);
    }

    if(flagUsingFFMpeg) {
      /** setting the input audio format in file reader */
      DEBUG(DEB_LEV_SIMPLE_SEQ,"FileName Param index : %x \n",eIndexParamFilename);
      err = OMX_SetParameter(appPriv->filereaderhandle,eIndexParamFilename,input_file);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"\n error in input audio format - exiting\n");
        exit(1);
      }
    }
    
    if (flagUsingFFMpeg) {
      DEBUG(DEB_LEV_SIMPLE_SEQ,"Sending Port Enable Command State Idle\n");

      err = OMX_SendCommand(appPriv->audiodechandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
      tsem_down(appPriv->decoderEventSem);

      err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandPortEnable, 0, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"file reader port enable failed\n");
			  exit(1);
      }
      err = OMX_SendCommand(appPriv->audiodechandle, OMX_CommandPortEnable, OMX_ALL, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"audio decoder port enable failed\n");
			  exit(1);
      }

      err = OMX_SendCommand(appPriv->volumehandle, OMX_CommandPortEnable, 0, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"audio sink port enable failed\n");
			  exit(1);
      }
      
      DEBUG(DEB_LEV_SIMPLE_SEQ,"Waiting File reader Port Disable event \n");
      /*Wait for File Reader Ports Disable Event*/
      tsem_down(appPriv->filereaderEventSem);
      DEBUG(DEB_LEV_SIMPLE_SEQ,"File reader Port Disable State Idle\n");
      /*Wait for Audio Decoder Ports Disable Event*/
      tsem_down(appPriv->decoderEventSem);
      tsem_down(appPriv->decoderEventSem);
      
      tsem_down(appPriv->volumeEventSem);

      
    }

    if(flagUsingFFMpeg) {
      err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"file reader state executing failed\n");
			  exit(1);
      }
      /*Wait for File reader state change to executing*/
      tsem_down(appPriv->filereaderEventSem);
      DEBUG(DEFAULT_MESSAGES,"File reader executing state \n");
    }

    err = OMX_SendCommand(appPriv->audiodechandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
    if(err != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR,"audio decoder state executing failed\n");
      exit(1);
    }
    
    DEBUG(DEB_LEV_SIMPLE_SEQ,"Waiting for audio dec state exec\n");
    /*Wait for decoder state change to executing*/
    tsem_down(appPriv->decoderEventSem);

    DEBUG(DEB_LEV_SIMPLE_SEQ,"All Component state changed to Executing\n");
    
    DEBUG(DEFAULT_MESSAGES,"Waiting for  EOS = %d\n",appPriv->eofSem->semval);

    if (seek==1) {

      DEBUG(DEFAULT_MESSAGES,"Sleeping for 5 Secs \n");
      /* Play for 5 Secs */
      sleep(5);
      DEBUG(DEFAULT_MESSAGES,"Sleep for 5 Secs is over\n");

      /*Then Pause the filereader component*/
      err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandStateSet, OMX_StatePause, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"file reader state executing failed\n");
			  exit(1);
      }
      /*Wait for File reader state change to Pause*/
      tsem_down(appPriv->filereaderEventSem);

      setHeader(&sTimeStamp, sizeof(OMX_TIME_CONFIG_TIMESTAMPTYPE));
      sTimeStamp.nPortIndex=0;
      /*Seek to 30 secs and play for 10 secs*/
      sTimeStamp.nTimestamp = 2351*38*30; // 23.51ms*38fps*30secs
      //sTimeStamp.nTimestamp = 2351*38*60*3; // 23.51ms*38fps*60secs*4mins
      DEBUG(DEFAULT_MESSAGES, "nTimestamp %llx \n", sTimeStamp.nTimestamp);
      err = OMX_SetConfig(appPriv->filereaderhandle, OMX_IndexConfigTimePosition, &sTimeStamp);
      if(err!=OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"Error %08x In OMX_SetParameter 0 \n",err);
      }

      err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"file reader state executing failed\n");
			  exit(1);
      }
      /*Wait for File reader state change to Pause*/
      tsem_down(appPriv->filereaderEventSem);

      DEBUG(DEFAULT_MESSAGES,"Sleeping for 10 Secs \n");
      /*Play for 10 secs*/
      sleep(10);
      DEBUG(DEFAULT_MESSAGES,"Sleep for 10 Secs is over\n");

      if(!bEOS) {
        /*Then Pause the filereader component*/
        err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandStateSet, OMX_StatePause, NULL);
        if(err != OMX_ErrorNone) {
          DEBUG(DEB_LEV_ERR,"file reader state executing failed\n");
			    exit(1);
        }
        /*Wait for File reader state change to Pause*/
        tsem_down(appPriv->filereaderEventSem);

        /*Seek to 5 mins or EOF*/
        sTimeStamp.nTimestamp = 2351*38*60*5; // 23.51ms*38fps*30secs
        //sTimeStamp.nTimestamp = 2351*38*60*3; // 23.51ms*38fps*60secs*4mins
        DEBUG(DEFAULT_MESSAGES, "nTimestamp %llx \n", sTimeStamp.nTimestamp);
        err = OMX_SetConfig(appPriv->filereaderhandle, OMX_IndexConfigTimePosition, &sTimeStamp);
        if(err!=OMX_ErrorNone) {
          DEBUG(DEB_LEV_ERR,"Error %08x In OMX_SetParameter 0 \n",err);
        }

        err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
        if(err != OMX_ErrorNone) {
          DEBUG(DEB_LEV_ERR,"file reader state executing failed\n");
			    exit(1);
        }
        /*Wait for File reader state change to Pause*/
        tsem_down(appPriv->filereaderEventSem);
      }
    }

    tsem_down(appPriv->eofSem);

    DEBUG(DEFAULT_MESSAGES,"Received EOS \n");
    /*Send Idle Command to all components*/
    DEBUG(DEFAULT_MESSAGES, "The execution of the decoding process is terminated\n");
    if(flagUsingFFMpeg) {
      err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
    }
    err = OMX_SendCommand(appPriv->audiodechandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
    
    if(flagUsingFFMpeg) {
      tsem_down(appPriv->filereaderEventSem);
      DEBUG(DEFAULT_MESSAGES,"File reader idle state \n");
    }
    tsem_down(appPriv->decoderEventSem);
    
    DEBUG(DEFAULT_MESSAGES, "All component Transitioned to Idle\n");

  } /*Loop While Play List*/

  if (flagPlaybackOn) {
    err = OMX_SendCommand(appPriv->volumehandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
    err = OMX_SendCommand(appPriv->audiosinkhandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
  }

  if (flagPlaybackOn) {
    tsem_down(appPriv->volumeEventSem);
    tsem_down(appPriv->sinkEventSem);
  }
  /*Send Loaded Command to all components*/
  if(flagUsingFFMpeg) {
    err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
  }
  err = OMX_SendCommand(appPriv->audiodechandle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
  if (flagPlaybackOn) {
    err = OMX_SendCommand(appPriv->volumehandle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
    err = OMX_SendCommand(appPriv->audiosinkhandle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
  }

  DEBUG(DEFAULT_MESSAGES, "Audio dec to loaded\n");

  if(flagUsingFFMpeg) {
    tsem_down(appPriv->filereaderEventSem);
    DEBUG(DEFAULT_MESSAGES,"File reader loaded state \n");
  }
  tsem_down(appPriv->decoderEventSem);
  if (flagPlaybackOn) {
    tsem_down(appPriv->volumeEventSem);
    tsem_down(appPriv->sinkEventSem);
  }

  if(input_file!=NULL) {
    free(input_file);
    input_file=NULL;
  }

  closedir(dirp);

  DEBUG(DEFAULT_MESSAGES, "All components released\n");

  /** freeing all handles and deinit omx */
  OMX_FreeHandle(appPriv->audiodechandle);

  DEBUG(DEB_LEV_SIMPLE_SEQ, "audiodec dec freed\n");
  
  if(flagUsingFFMpeg) {
    OMX_FreeHandle(appPriv->filereaderhandle);
    DEBUG(DEB_LEV_SIMPLE_SEQ, "filereader freed\n");
  }

  if (flagPlaybackOn) {
    OMX_FreeHandle(appPriv->volumehandle);
    DEBUG(DEB_LEV_SIMPLE_SEQ, "volume component freed\n");
    OMX_FreeHandle(appPriv->audiosinkhandle);
    DEBUG(DEB_LEV_SIMPLE_SEQ, "audiosink freed\n");
  }

  OMX_Deinit();

  DEBUG(DEB_LEV_SIMPLE_SEQ, "All components freed. Closing...\n");

  free(appPriv->filereaderEventSem);
  appPriv->filereaderEventSem = NULL;

  free(appPriv->decoderEventSem);
  appPriv->decoderEventSem = NULL;
  if (flagPlaybackOn) {
    free(appPriv->volumeEventSem);
    appPriv->volumeEventSem = NULL;

    free(appPriv->sinkEventSem);
    appPriv->sinkEventSem = NULL;
  }

  free(appPriv->eofSem);
  appPriv->eofSem = NULL;
  free(appPriv);
  appPriv = NULL;

  if(input_file) {
    free(input_file);
  }

  return 0;
}