/* detect the compliance profile(s) that the component is eligible for */
OMX_U32 DetectComplianceProfile(OMX_STRING sArgument)
{
    OMX_U32 detectedCompliance;
    OMX_HANDLETYPE hThread, hComp, hTTC;
    OMX_CALLBACKTYPE oDummyCallbacks;
    OMX_TIME_CONFIG_TIMESTAMPTYPE oTimeStamp;
    OMX_TIME_CONFIG_ACTIVEREFCLOCKTYPE oRefClock;

    detectedCompliance = OMX_CONF_TestFlag_Base|OMX_CONF_TestFlag_AutoOutput;

    /* try to create a thread -> implies threading compliance */
    if (OMX_ErrorNone == OMX_OSAL_ThreadCreate( DummyThreadFunction, 0, 0, &hThread)){
        if (OMX_ErrorNone == OMX_OSAL_ThreadDestroy( hThread)){
            detectedCompliance |= OMX_CONF_TestFlag_Threaded;
        }
    }
    oDummyCallbacks.EmptyBufferDone = StubbedEmptyBufferDone;
    oDummyCallbacks.FillBufferDone = StubbedFillBufferDone;
    oDummyCallbacks.EventHandler = StubbedEventHandler;
    if (OMX_ErrorNone != OMX_Init()){
        return 0;
    }
    if (OMX_ErrorNone != OMX_GetHandle(&hComp, sArgument, NULL, &oDummyCallbacks)){
        OMX_Deinit();
        return 0;
    }
    if (OMX_ErrorNone != OMX_CONF_GetTunnelTestComponentHandle(&hTTC, NULL, &oDummyCallbacks)){
        OMX_FreeHandle(hComp);
        OMX_Deinit();
        return 0;
    }

    if (OMX_ErrorNone == OMX_CONF_TTCConnectAllPorts(hTTC, hComp))
    {
        INIT_PARAM(oRefClock);
        INIT_PARAM(oTimeStamp);
        oTimeStamp.nPortIndex = 0;

        detectedCompliance |= OMX_CONF_TestFlag_Interop;

        /* try to set active ref clock -> implies clock component compliance */
        if (OMX_ErrorUnsupportedIndex != OMX_SetConfig(hComp, OMX_IndexConfigTimeActiveRefClock, &oRefClock)){
            detectedCompliance &= ~OMX_CONF_TestFlag_AutoOutput; /* only clock component doesn't have autooutput */
            detectedCompliance |=  OMX_CONF_TestFlag_ClockComp; 
        } 

        /* try to set time position -> implies seeking compliance */
        if (OMX_ErrorUnsupportedIndex != OMX_SetConfig(hComp, OMX_IndexConfigTimePosition, &oTimeStamp)){
            detectedCompliance |=  OMX_CONF_TestFlag_Seeking; 
        }
    }

    OMX_CONF_FreeTunnelTestComponentHandle(hTTC);
    OMX_FreeHandle(hComp);
    OMX_Deinit();

    return detectedCompliance;
}
Пример #2
0
/* ======================================================================
FUNCTION
  OMX_DeInit

DESCRIPTION
  DeInitialize all the the relevant OMX components.

PARAMETERS
  None

RETURN VALUE
  Error None.
========================================================================== */
OMX_API OMX_ERRORTYPE OMX_APIENTRY OMX_Deinit()
{

#if 0

	int err;
	unsigned i=0,j=0;
	OMX_ERRORTYPE eRet;

	/* Free the dangling handles here if any */
	for(i=0; i< SIZE_OF_CORE; i++)
	{
		for(j=0; j< OMX_COMP_MAX_INST; j++)
		{
			if(core[i].inst[j])
			{
				logi("OMX DeInit: Freeing handle for %s\n", core[i].name);

				/* Release the component and unload dynmaic library */
				eRet = OMX_FreeHandle(core[i].inst[j]);
				if(eRet != OMX_ErrorNone)
					return eRet;
			}
		}
	}
#endif

	return OMX_ErrorNone;
}
Пример #3
0
END_TEST
START_TEST (test_ilcore_init_and_deinit_get_hdl_free_hdl)
{
  OMX_ERRORTYPE error = OMX_ErrorNone;
  OMX_HANDLETYPE p_hdl = NULL;
  OMX_U32 appData;
  OMX_CALLBACKTYPE callBacks;

  error = OMX_Init ();
  fail_if (error != OMX_ErrorNone);

  error = OMX_GetHandle (&p_hdl,
                         TIZ_CORE_TEST_COMPONENT_NAME,
                         (OMX_PTR *) (&appData), &callBacks);
  TIZ_LOG (TIZ_PRIORITY_TRACE, "OMX_GetHandle error [%s]", tiz_err_to_str (error));
  fail_if (error != OMX_ErrorNone);

  TIZ_LOG (TIZ_PRIORITY_TRACE, "p_hdl [%p]", p_hdl);

  error = OMX_FreeHandle (p_hdl);
  fail_if (error != OMX_ErrorNone);

  error = OMX_Deinit ();
  fail_if (error != OMX_ErrorNone);
}
/** mm_jpegdec_session_destroy:
 *
 *  Arguments:
 *    @p_session: job session
 *
 *  Return:
 *       none
 *
 *  Description:
 *       Destroy a jpeg encode session
 *
 **/
void mm_jpegdec_session_destroy(mm_jpeg_job_session_t* p_session)
{
  OMX_ERRORTYPE rc = OMX_ErrorNone;

  CDBG("%s:%d] E", __func__, __LINE__);
  if (NULL == p_session->omx_handle) {
    CDBG_ERROR("%s:%d] invalid handle", __func__, __LINE__);
    return;
  }

  rc = mm_jpeg_session_change_state(p_session, OMX_StateIdle, NULL);
  if (rc) {
    CDBG_ERROR("%s:%d] Error", __func__, __LINE__);
  }

  rc = mm_jpeg_session_change_state(p_session, OMX_StateLoaded,
    mm_jpegdec_session_free_buffers);
  if (rc) {
    CDBG_ERROR("%s:%d] Error", __func__, __LINE__);
  }

  rc = OMX_FreeHandle(p_session->omx_handle);
  if (0 != rc) {
    CDBG_ERROR("%s:%d] OMX_FreeHandle failed (%d)", __func__, __LINE__, rc);
  }
  p_session->omx_handle = NULL;


  pthread_mutex_destroy(&p_session->lock);
  pthread_cond_destroy(&p_session->cond);
  CDBG("%s:%d] X", __func__, __LINE__);
}
Пример #5
0
void
g_omx_core_deinit (GOmxCore *core)
{
    if (!core->imp)
        return;

    core_for_each_port (core, g_omx_port_free);
    g_ptr_array_clear (core->ports);

    if (core->omx_state == OMX_StateLoaded ||
        core->omx_state == OMX_StateInvalid)
    {
        if (core->omx_handle)
        {
            #ifdef USE_STATIC
            core->omx_error = OMX_FreeHandle (core->omx_handle);
            #else
            core->omx_error = core->imp->sym_table.free_handle (core->omx_handle);
            #endif
            GST_DEBUG_OBJECT (core->object, "OMX_FreeHandle(%p) -> %s",
                core->omx_handle, g_omx_error_to_str (core->omx_error));
            core->omx_handle = NULL;
        }
    }

    g_omx_release_imp (core->imp);
    core->imp = NULL;
}
OMX_ERRORTYPE load_component(HTEST *hTest)
{
	OMX_ERRORTYPE ret = OMX_ErrorNone;
	OMX_HANDLETYPE hComponent = NULL;
	OMX_PARAM_PORTDEFINITIONTYPE sPortDef;
	OMX_U32 i;

	ret = OMX_GetHandle(&hComponent, hTest->name, hTest, &gCallBacks);
	if(ret != OMX_ErrorNone)
	{
		printf("Load component %s failed.\n", hTest->name);
		return ret;
	}

	hTest->hComponent = (OMX_COMPONENTTYPE*)hComponent;
	hTest->nPorts = get_component_ports(hComponent);
	OMX_INIT_STRUCT(&sPortDef, OMX_PARAM_PORTDEFINITIONTYPE);
	for(i=0; i<hTest->nPorts; i++)
	{
		sPortDef.nPortIndex = i;
		OMX_GetParameter(hComponent, OMX_IndexParamPortDefinition, &sPortDef);
		if (sPortDef.eDomain == OMX_PortDomainAudio)
			hTest->nAudioTrackNum = i;
		if (sPortDef.eDomain == OMX_PortDomainVideo)
			hTest->nVideoTrackNum = i;

		hTest->PortDir[i] = sPortDef.eDir;
		if(hTest->PortDir[i] == OMX_DirInput)
			hTest->bAllocater[i] = OMX_FALSE;
		if(hTest->PortDir[i] == OMX_DirOutput)
			hTest->bAllocater[i] = OMX_TRUE;
	}
	OMX_PARAM_CONTENTURITYPE *content = NULL;

	content =(OMX_PARAM_CONTENTURITYPE *) fsl_osal_malloc_new(sizeof(OMX_PARAM_CONTENTURITYPE) + 1024);
	if (!content)
		return OMX_ErrorInsufficientResources;

	fsl_osal_memset(content, 0 , sizeof(OMX_PARAM_CONTENTURITYPE)+1024);
	OMX_INIT_STRUCT(content,OMX_PARAM_CONTENTURITYPE);
	char* uri = (char*)&(content->contentURI);
	fsl_osal_memcpy(uri, hTest->media_name, strlen(hTest->media_name)+1);

	ret = OMX_SetParameter(hTest->hComponent,OMX_IndexParamContentURI,content);
	if (ret != OMX_ErrorNone)
	{
		OMX_FreeHandle(hTest->hComponent);
		hTest->hComponent = NULL;
		return ret;
	}




	fsl_osal_thread_create(&hTest->pThreadId, NULL, process_thread, hTest);

	return OMX_ErrorNone;
}
Пример #7
0
void
omx_component_destroy(omx_component_t *oc)
{
  omxchk(OMX_FreeHandle(oc->oc_handle));

  free(oc->oc_name);
  hts_cond_destroy(&oc->oc_event_cond);
  free(oc);
}
OMX_ERRORTYPE unload_component(HTEST *hTest)
{
	OMX_FreeHandle(hTest->hComponent);

	MSG sMsg;
	sMsg.type = EXIT;
	hTest->pMsgQ->Add(&sMsg);
	fsl_osal_thread_destroy(hTest->pThreadId);

	return OMX_ErrorNone;
}
void terminate() {
	print_log("On terminating...");

	OMX_STATETYPE state;
	OMX_BOOL bWaitForCamera, bWaitForRender;

	// Execute -> Idle
	bWaitForCamera = bWaitForRender = OMX_FALSE;
	if(isState(mContext.pCamera, OMX_StateExecuting)) {
		OMX_SendCommand(mContext.pCamera, OMX_CommandStateSet, OMX_StateIdle, NULL);
		bWaitForCamera = OMX_TRUE;
	}
	if(isState(mContext.pRender, OMX_StateExecuting)) {
		OMX_SendCommand(mContext.pRender, OMX_CommandStateSet, OMX_StateIdle, NULL);
		bWaitForRender = OMX_TRUE;
	}
	if(bWaitForCamera) wait_for_state_change(OMX_StateIdle, mContext.pCamera, NULL);
	if(bWaitForRender) wait_for_state_change(OMX_StateIdle, mContext.pRender, NULL);

	// Idle -> Loaded
	bWaitForCamera = bWaitForRender = OMX_FALSE;
	if(isState(mContext.pCamera, OMX_StateIdle)) {
		OMX_SendCommand(mContext.pCamera, OMX_CommandStateSet, OMX_StateLoaded, NULL);
		bWaitForCamera = OMX_TRUE;
	}
	if(isState(mContext.pRender, OMX_StateIdle)) {
		OMX_SendCommand(mContext.pRender, OMX_CommandStateSet, OMX_StateLoaded, NULL);
		bWaitForRender = OMX_TRUE;
	}
	if(bWaitForCamera) wait_for_state_change(OMX_StateLoaded, mContext.pCamera, NULL);
	if(bWaitForRender) wait_for_state_change(OMX_StateLoaded, mContext.pRender, NULL);

	// Loaded -> Free
	if(isState(mContext.pCamera, OMX_StateLoaded)) OMX_FreeHandle(mContext.pCamera);
	if(isState(mContext.pRender, OMX_StateLoaded)) OMX_FreeHandle(mContext.pRender);

	OMX_Deinit();

	print_log("Press enter to terminate.");
	getchar();
}
Пример #10
0
nsresult
PureOmxPlatformLayer::Shutdown()
{
  LOG("");
  if (mComponent) {
    OMX_FreeHandle(mComponent);
    mComponent = nullptr;
  }
  mPromiseLayer = nullptr;
  mDataDecoder = nullptr;
  return NS_OK;
}
Пример #11
0
	CComponent::~CComponent()
	{
		try
		{
			ChangeState(OMX_StateIdle);
			CHECK_OMX(OMX_FreeHandle(m_hComponent), "failed to free component");
		}
		catch (std::exception& Exception)
		{
			std::cerr << "Error: " << Exception.what() << std::endl;
		}
	}
Пример #12
0
OMX_ERRORTYPE test_OpenClose(OMX_STRING component_name) {
    OMX_ERRORTYPE err = OMX_ErrorNone;

    DEBUG(DEFAULT_MESSAGES, "GENERAL TEST %s\n",__func__);
    err = OMX_GetHandle(&appPriv->audiosrchandle, component_name, NULL, &audiosrccallbacks);
    if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR, "No component found\n");
    } else {
        err = OMX_FreeHandle(appPriv->audiosrchandle);
    }
    DEBUG(DEFAULT_MESSAGES, "GENERAL TEST %s result %i\n", __func__, err);
    return err;
}
Пример #13
0
omxil_comp::~omxil_comp()
{
	OMX_ERRORTYPE result;

	//Remove buffer list
	for (auto& elem : map_buflist) {
		delete elem.second;
	}

	result = OMX_FreeHandle(comp);
	if (result != OMX_ErrorNone) {
		fprintf(stderr, "OMX_FreeHandle failed.");
	}
}
    OMX_ERRORTYPE ResourceExhaustionTest_UNLOAD(ResourceExhaustionTestContext *pCtxt)
    {
        OMX_ERRORTYPE eError = OMX_ErrorNone;
        if (pCtxt->hComp[pCtxt->nInst])
        {
            eError = OMX_FreeHandle(pCtxt->hComp[pCtxt->nInst]);
            OMX_CONF_BAIL_IF_ERROR(eError);
        }
        if (pCtxt->hWComp[pCtxt->nInst])
        {
            eError = OMX_CONF_ComponentTracerDestroy(pCtxt->hWComp[pCtxt->nInst]);
            OMX_CONF_BAIL_IF_ERROR(eError);
        }
        pCtxt->hComp[pCtxt->nInst] = NULL;
        pCtxt->hWComp[pCtxt->nInst] = NULL;

OMX_CONF_TEST_BAIL:
        return eError;
    }
Пример #15
0
void ilcore_uninit_comp(ilcore_comp_h h)
{
    OMX_ERRORTYPE err;
    ilcore_comp_ctx_t  *ctx = (ilcore_comp_ctx_t *)h;

    if (!ctx)
        return;

    if (ctx->name)
        free(ctx->name);

    err = OMX_FreeHandle(ctx->handle);
    if (err != OMX_ErrorNone)
        DBG_E("OMX_FreeHandle failed. err=%d\n", err);

    msleep_uninit(ctx->event_sleep);
    slist_uninit(ctx->event_list);

    free(ctx);
}
Пример #16
0
bool COMXCoreComponent::Deinitialize(bool free_component /* = false */)
{
    OMX_ERRORTYPE omx_err;

    m_exit = true;

    m_flush_input   = true;
    m_flush_output  = true;

    if(m_handle && m_DllOMXOpen)
    {
        FlushAll();
        FreeOutputBuffers();
        FreeInputBuffers();

        TransitionToStateLoaded();

        if(free_component)
        {
            Logger::LogOut(LOG_LEVEL_DEBUG, "COMXCoreComponent::Deinitialize : %s handle %p dllopen : %d",
                    m_componentName.c_str(), m_handle, m_DllOMXOpen);
            omx_err = OMX_FreeHandle(m_handle);
            if (omx_err != OMX_ErrorNone)
            {
                Logger::LogOut(LOG_LEVEL_ERROR, "COMXCoreComponent::Deinitialize - failed to free handle for component %s omx_err(0x%08x)",
                        m_componentName.c_str(), omx_err);
            }
            m_handle = NULL;

            m_input_port      = 0;
            m_output_port     = 0;
            m_componentName   = "";
            m_resource_error  = false;
        }
    }

    return true;
}
Пример #17
0
int main(int argc, char *argv[])
{
	AVFormatContext	*ic;
	char		*iname;
	char		*oname;
	char		*size;
	int		err;
	int		vidindex;
	int		i, j;
	OMX_ERRORTYPE	oerr;
	OMX_HANDLETYPE	m2 = NULL, m4 = NULL, resize = NULL;
	OMX_VIDEO_PARAM_PORTFORMATTYPE	*pfmt;
	OMX_PORT_PARAM_TYPE		*porttype;
	OMX_PARAM_PORTDEFINITIONTYPE	*portdef;
	OMX_BUFFERHEADERTYPE		*decbufs;
	OMX_VIDEO_PORTDEFINITIONTYPE	*viddef;
	OMX_VIDEO_PARAM_PROFILELEVELTYPE *level;
	int		decportidx = 200;
	int		resizeportidx = 60;
	int		encportidx = 130;
	int		fd;
	time_t		start, end;
	int		offset;
	AVPacket	*p, *rp;
	int		ish264;
	int		filtertest;
	int		opt;
	ILCLIENT_T	*client;

	if (argc < 3)
		usage(argv[0]);

	ctx.bitrate = 2*1024*1024;
	ctx.verbose = 0;
	ctx.width = 0;
	ctx.height = 0;

	while ((opt = getopt(argc, argv, ":b:vs:")) != -1) {
		switch (opt) {
		case 'b':	//bitrate
			ctx.bitrate = atoi(optarg);
			printf("bitrate = %d\n", ctx.bitrate);
			break;
		case 'v':	//verbose`
			ctx.verbose = 1;
			break;
		case 's':	//WxH
			ctx.width = atoi(optarg);
			if ((atoi(optarg) % 16) != 0) {
				printf("W = %d is not a multiple of 16\n", ctx.width);
				usage(argv[0]);
			}
			if (ctx.width <16 || ctx.width > 1080) {
				printf("W = %d should be between 16 and 1080\n", ctx.width);
				usage(argv[0]);
			}	
			printf("W = %d\n", ctx.width);
			if ((size = strchr(optarg, 'x')) == NULL) {
				printf("wrong size parameter (no 'x') exiting\n");
				usage(argv[0]);
			}
			ctx.height = atoi(size+1);
			if ((atoi(size+1) % 16) != 0) {
				printf("H = %d is not a multiple of 16\n", ctx.height);
				usage(argv[0]);
			}
			if (ctx.height <16 || ctx.height > 1080) {
				printf("H = %d should be between 16 and 1080\n", ctx.height);
				usage(argv[0]);
			}	
			printf("H = %d\n", ctx.height);
			break;
		case '?':
			usage(argv[0]);
		}
	}
	if ((client = ilclient_init()) == NULL)
		return -2;
	iname = argv[optind++];
	oname = argv[optind++];

	MAKEME(porttype, OMX_PORT_PARAM_TYPE);
	MAKEME(portdef, OMX_PARAM_PORTDEFINITIONTYPE);
	MAKEME(pfmt, OMX_VIDEO_PARAM_PORTFORMATTYPE);

	av_register_all();

	ic = NULL;
	ish264 = 0;
	pthread_mutex_init(&ctx.lock, NULL);

#if 0
	fmt = av_oformat_next(fmt);
	while (fmt) {
		printf("Found '%s'\t\t'%s'\n", fmt->name, fmt->long_name);
		fmt = av_oformat_next(fmt);
	}
#endif

	/* Input init: */

	if ((err = avformat_open_input(&ic, iname, NULL, NULL) != 0)) {
		fprintf(stderr, "Failed to open '%s': %s\n", iname,
			strerror(err));
		exit(1);
	}
	ctx.ic = ic;

	if (avformat_find_stream_info(ic, NULL) < 0) {
		fprintf(stderr, "Failed to find streams in '%s'\n", iname);
		exit(1);
	}

	av_dump_format(ic, 0, iname, 0);

	vidindex = av_find_best_stream(ic, AVMEDIA_TYPE_VIDEO, -1, -1,
		NULL, 0);
	if (vidindex < 0) {
		fprintf(stderr, "Failed to find a video stream in '%s'\n",
			iname);
		exit(1);
	}
	printf("Found a video at index %d\n", vidindex);

	printf("Frame size: %dx%d\n", ic->streams[vidindex]->codec->width, 
		ic->streams[vidindex]->codec->height);
	ish264 = (ic->streams[vidindex]->codec->codec_id == CODEC_ID_H264);

	/* Output init: */
	ctx.fd = fd = open(oname, O_CREAT | O_LARGEFILE | O_WRONLY | O_TRUNC,
			0666);
	printf("File descriptor %d\n", fd);


#if 0
	avformat_alloc_output_context(&oc, NULL, /*NULL,*/ oname);
	if (!oc) {
		printf("Couldn't determine output from '%s'; using MPEG.\n",
			oname);
		avformat_alloc_output_context(&oc, NULL, /*"matroska",*/ oname);
	}
#endif
//	if (!oc)
//		exit(1);
	
//	fmt = oc->oformat;
	
	for (i = 0; i < ic->nb_streams; i++) {
		printf("Found stream %d, context %p\n",
			ic->streams[i]->index, ic->streams[i]->codec);
	}

	bcm_host_init();
	OERR(OMX_Init(), ctx.verbose);
	OERR(OMX_GetHandle(&m2, DECNAME, &ctx, &decevents), ctx.verbose);
	OERR(OMX_GetHandle(&m4, ENCNAME, &ctx, &encevents), ctx.verbose);
	OERR(OMX_GetHandle(&resize, RESIZENAME, &ctx, &resizeevents), ctx.verbose);
	ctx.m2 = m2;
	ctx.m4 = m4;
	ctx.resize = resize;

	if (ctx.verbose) printf("Obtained handles.  %p decode, %p resize, %p encode\n",
		m2, resize, m4);

	OERR(OMX_GetParameter(m2, OMX_IndexParamVideoInit, porttype), ctx.verbose);
	if (ctx.verbose) printf("Found %d ports, starting at %d (%x) on decoder\n",
		porttype->nPorts, porttype->nStartPortNumber,
		porttype->nStartPortNumber);
	ctx.decportidx = decportidx = porttype->nStartPortNumber;

	OERR(OMX_GetParameter(resize, OMX_IndexParamImageInit, porttype), ctx.verbose);
	if (ctx.verbose) printf("Found %d ports, starting at %d (%x) on resizer\n",
		porttype->nPorts, porttype->nStartPortNumber,
		porttype->nStartPortNumber);
	ctx.resizeportidx = resizeportidx = porttype->nStartPortNumber;

	OERR(OMX_GetParameter(m4, OMX_IndexParamVideoInit, porttype), ctx.verbose);
	if (ctx.verbose) printf("Found %d ports, starting at %d (%x) on encoder\n",
		porttype->nPorts, porttype->nStartPortNumber,
		porttype->nStartPortNumber);
	ctx.encportidx = encportidx = porttype->nStartPortNumber;
	free(porttype);

	OERR(OMX_SendCommand(m2, OMX_CommandPortDisable, decportidx, NULL), ctx.verbose);
	OERR(OMX_SendCommand(m2, OMX_CommandPortDisable, decportidx+1, NULL), ctx.verbose);
	OERR(OMX_SendCommand(resize, OMX_CommandPortDisable, resizeportidx, NULL), ctx.verbose);
	OERR(OMX_SendCommand(resize, OMX_CommandPortDisable, resizeportidx+1, NULL), ctx.verbose);
	OERR(OMX_SendCommand(m4, OMX_CommandPortDisable, encportidx, NULL), ctx.verbose);
	OERR(OMX_SendCommand(m4, OMX_CommandPortDisable, encportidx+1, NULL), ctx.verbose);

	portdef->nPortIndex = decportidx;
	OERR(OMX_GetParameter(m2, OMX_IndexParamPortDefinition, portdef), ctx.verbose);
	viddef = &portdef->format.video;
	viddef->nFrameWidth = ic->streams[vidindex]->codec->width;
	viddef->nFrameHeight = ic->streams[vidindex]->codec->height;
	printf("Mapping codec %d to %d\n",
		ic->streams[vidindex]->codec->codec_id,
		mapcodec(ic->streams[vidindex]->codec->codec_id));
	viddef->eCompressionFormat = 
		mapcodec(ic->streams[vidindex]->codec->codec_id);
	viddef->bFlagErrorConcealment = 0;
//	viddef->xFramerate = 25<<16;
	OERR(OMX_SetParameter(m2, OMX_IndexParamPortDefinition, portdef), ctx.verbose);
	free(portdef);

#if 0
/* It appears these have limited effect: */
	dataunit->nPortIndex = decportidx;
	dataunit->eUnitType = OMX_DataUnitCodedPicture;
	dataunit->eEncapsulationType = OMX_DataEncapsulationGenericPayload;
	OERR(OMX_SetParameter(m2, OMX_IndexParamBrcmDataUnit, dataunit), ctx.verbose);

	if (ish264) {
		naltype->nPortIndex = decportidx;
		naltype->eNaluFormat = OMX_NaluFormatStartCodes;
		OERR(OMX_SetParameter(m2, OMX_IndexParamNalStreamFormatSelect, naltype), ctx.verbose);
	}
#endif

	MAKEME(level, OMX_VIDEO_PARAM_PROFILELEVELTYPE);
	level->nPortIndex = encportidx+1;
/* Dump what the encoder is capable of: */
	if (ctx.verbose) print_codecs();
	if (ctx.verbose) {
		for (oerr = OMX_ErrorNone, i = 0; oerr == OMX_ErrorNone; i++) {
			pfmt->nIndex = i;
			oerr = OMX_GetParameter(m4, OMX_IndexParamVideoPortFormat, pfmt);
			if (oerr == OMX_ErrorNoMore)
				break;
			printf("Codecs supported:\n"
				"\tIndex:\t\t%d\n"
				"\tCodec:\t\t%d (%x)\n"
				"\tColour:\t\t%d\n"
				"\tFramerate:\t%x (%f)\n",
				pfmt->nIndex,
				pfmt->eCompressionFormat, pfmt->eCompressionFormat,
				pfmt->eColorFormat,
				pfmt->xFramerate,
				((float)pfmt->xFramerate/(float)65536));
		}

		for (oerr = OMX_ErrorNone, i = 0; oerr == OMX_ErrorNone; i++) {
			level->nProfileIndex = i;
			oerr = OMX_GetParameter(m4,
				OMX_IndexParamVideoProfileLevelQuerySupported,
				level);
			if (oerr == OMX_ErrorNoMore)
				break;
			printf("Levels supported:\n"
				"\tIndex:\t\t%d\n"
				"\tProfile:\t%d\n"
				"\tLevel:\t\t%d\n",
				level->nProfileIndex,
				level->eProfile,
				level->eLevel);
		}
	}
	free(pfmt);
	free(level);

/* Dump current port states: */
	if (ctx.verbose) {
		dumpport(m2, decportidx);
		dumpport(m2, decportidx+1);
		dumpport(resize, resizeportidx);
		dumpport(resize, resizeportidx+1);
		dumpport(m4, encportidx);
		dumpport(m4, encportidx+1);
	}

	OERR(OMX_SendCommand(m2, OMX_CommandStateSet, OMX_StateIdle, NULL), ctx.verbose);

	decbufs = allocbufs(m2, decportidx, 1);

/* Start the initial loop.  Process until we have a state change on port 131 */
	ctx.decstate = DECINIT;
	ctx.encstate = ENCPREINIT;
	OERR(OMX_SendCommand(m2, OMX_CommandStateSet, OMX_StateExecuting, NULL), ctx.verbose);

	rp = calloc(sizeof(AVPacket), 1);
	filtertest = ish264;

	for (offset = i = j = 0; ctx.decstate != DECFAILED; i++, j++) {
		int rc;
		int k;
		int size, nsize;
		OMX_BUFFERHEADERTYPE *spare;

		if (offset == 0 && ctx.decstate != DECFLUSH) {
			rc = av_read_frame(ic, rp);
			if (rc != 0) {
				if (ic->pb->eof_reached)
					ctx.decstate = DECFLUSH;
				break;
			}
			if (rp->stream_index != vidindex) {
				i--;
				av_free_packet(rp);
				continue;
			}
			size = rp->size;
			ctx.fps++;
			ctx.framecount++;

			if (ish264 && filtertest) {
				filtertest = 0;
				ctx.bsfc = dofiltertest(rp);
			}
			if (ctx.bsfc) {
				p = filter(&ctx, rp);
			} else {
				p = rp;
			}
		}

		switch (ctx.decstate) {
		case DECTUNNELSETUP:
			start = time(NULL);
			//printf("NOW to CONFIGURE !!!!!!!!!!!!!!\n\n");
			configure(&ctx);
			ctx.decstate = DECRUNNING;
			break;
		case DECFLUSH:
			size = 0;
			/* Add the flush code here */
			printf("IN FLUSH NOW\n\n");
			break;
		case DECINIT:
			if (i < 120) /* Bail; decoder doesn't like it */
				break;
			ctx.decstate = DECFAILED;
			/* Drop through */
		case DECFAILED:
			fprintf(stderr, "Failed to set the parameters after "
					"%d video frames.  Giving up.\n", i);
			dumpport(m2, decportidx);
			dumpport(m2, decportidx+1);
			dumpport(resize, resizeportidx);
			dumpport(resize, resizeportidx+1);
			dumpport(m4, encportidx);
			dumpport(m4, encportidx+1);
			exit(1);
			break;
		default:
			break;	/* Shuts the compiler up */
		}

		for (spare = NULL; !spare; usleep(10)) {
			pthread_mutex_lock(&ctx.lock);
			spare = ctx.bufhead;
			ctx.bufhead = NULL;
			ctx.flags &= ~FLAGS_DECEMPTIEDBUF;
			pthread_mutex_unlock(&ctx.lock);
			while (spare) {
				write(fd, &spare->pBuffer[spare->nOffset],
					spare->nFilledLen);
				spare->nFilledLen = 0;
				spare->nOffset = 0;
				OERRq(OMX_FillThisBuffer(m4, spare));
				spare = spare->pAppPrivate;
			}

			spare = decbufs;
			for (k = 0; spare && spare->nFilledLen != 0; k++)
				spare = spare->pAppPrivate;
		}

		if (size > spare->nAllocLen) {
			nsize = spare->nAllocLen;
		} else {
			nsize = size;
		}

		if (ctx.decstate != DECFLUSH) {
			memcpy(spare->pBuffer, &(p->data[offset]), nsize);
			spare->nFlags = i == 0 ? OMX_BUFFERFLAG_STARTTIME : 0;
			spare->nFlags |= size == nsize ?
				OMX_BUFFERFLAG_ENDOFFRAME : 0;
		} else {
			spare->nFlags = OMX_BUFFERFLAG_STARTTIME |
					OMX_BUFFERFLAG_EOS;
		}
		spare->nFilledLen = nsize;
		spare->nOffset = 0;
		OERRq(OMX_EmptyThisBuffer(m2, spare));
		size -= nsize;
		if (size) {
			offset += nsize;
		} else {
			offset = 0;
			av_free_packet(p);
		}
	}

	close(fd);

	end = time(NULL);

	printf("Processed %d frames in %d seconds; %df/s\n",
		ctx.framecount, end-start, (ctx.framecount/(end-start)));

	// flush the encoder
//	OERR(OMX_SendCommand(m4, OMX_CommandFlush, encportidx, NULL), ctx.verbose);
//	OERR(OMX_SendCommand(m4, OMX_CommandFlush, encportidx+ctx.verbose, NULL), ctx.verbose);



	// tear down the tunnels
	OERR(OMX_SendCommand(m2, OMX_CommandStateSet, OMX_StateIdle, NULL), ctx.verbose);
	OERR(OMX_SendCommand(resize, OMX_CommandStateSet, OMX_StateIdle, NULL), ctx.verbose);
	OERR(OMX_SendCommand(m4, OMX_CommandStateSet, OMX_StateIdle, NULL), ctx.verbose);
	OERR(OMX_SendCommand(m2, OMX_CommandStateSet, OMX_StateLoaded, NULL), ctx.verbose);
	OERR(OMX_SendCommand(resize, OMX_CommandStateSet, OMX_StateLoaded, NULL), ctx.verbose);
	OERR(OMX_SendCommand(m4, OMX_CommandStateSet, OMX_StateLoaded, NULL), ctx.verbose);
	// free buffers
	vcos_free(decbufs);
	vcos_free(ctx.encbufs);
	// Apparantly the teardwon function is not implemented. Use setup function instead
	//OERR(OMX_TeardownTunnel(m2, decportidx+ctx.verbose, resize, resizeportidx), ctx.verbose);
	//OERR(OMX_TeardownTunnel(resize, resizeportidx+ctx.verbose, m4, encportidx), ctx.verbose);
	OERR(OMX_SendCommand(m2, OMX_CommandPortDisable, decportidx, NULL), ctx.verbose);
	OERR(OMX_SendCommand(m2, OMX_CommandPortDisable, decportidx+ctx.verbose, NULL), ctx.verbose);
	OERR(OMX_SendCommand(resize, OMX_CommandPortDisable, resizeportidx, NULL), ctx.verbose);
	OERR(OMX_SendCommand(resize, OMX_CommandPortDisable, resizeportidx+ctx.verbose, NULL), ctx.verbose);
	OERR(OMX_SendCommand(m4, OMX_CommandPortDisable, encportidx, NULL), ctx.verbose);
	OERR(OMX_SendCommand(m4, OMX_CommandPortDisable, encportidx+ctx.verbose, NULL), ctx.verbose);
//	ilclient_disable_port_buffers(m2, decportidx, NULL, NULL, NULL);
//	ilclient_disable_port_buffers(m4, encportidx, NULL, NULL, NULL);
	OERR(OMX_SetupTunnel(m2, decportidx+ctx.verbose, NULL, 0), ctx.verbose);
	OERR(OMX_SetupTunnel(resize, resizeportidx, NULL, 0), ctx.verbose);
	OERR(OMX_SetupTunnel(resize, resizeportidx+ctx.verbose, NULL, 0), ctx.verbose);
	OERR(OMX_SetupTunnel(m4, encportidx, NULL, 0), ctx.verbose);
	OERR(OMX_FreeHandle(m2), ctx.verbose);
	OERR(OMX_FreeHandle(resize), ctx.verbose);
	OERR(OMX_FreeHandle(m4), ctx.verbose);

//	free(porttype);
//	free(portdef);
//	free(pfmt);
//	free(level);
	return 0;
}
Пример #18
0
void *video_decode_test(void* arg) {
    bcm_host_init();

		CUBE_STATE_T *state = (CUBE_STATE_T *)arg;

    OMX_ERRORTYPE r;

    if((r = OMX_Init()) != OMX_ErrorNone) {
        omx_die(r, "OMX initalization failed");
    }

    // Init context
    appctx ctx;
    memset(&ctx, 0, sizeof(ctx));
    if(vcos_semaphore_create(&ctx.handler_lock, "handler_lock", 1) != VCOS_SUCCESS) {
        die("Failed to create handler lock semaphore");
    }

		ctx.eglImage = state->eglImage;

    // Init component handles
    OMX_CALLBACKTYPE callbacks;
    memset(&ctx, 0, sizeof(callbacks));
    callbacks.EventHandler = event_handler;
    callbacks.FillBufferDone = my_fill_buffer_done;

    init_component_handle("camera", &ctx.camera , &ctx, &callbacks);
    init_component_handle("egl_render", &ctx.render, &ctx, &callbacks);
    init_component_handle("null_sink", &ctx.null_sink, &ctx, &callbacks);
    init_component_handle("clock", &ctx.clock, &ctx, &callbacks);

    OMX_U32 screen_width = state->screen_width, screen_height = state->screen_height;
    if(graphics_get_display_size(DISPLAY_DEVICE, &screen_width, &screen_height) < 0) {
        die("Failed to get display size");
    }

    say("Configuring camera...");

    dump_port(ctx.clock, 80, OMX_TRUE);
    say("Default port definition for camera input port 73");
    dump_port(ctx.camera, 73, OMX_TRUE);
    say("Default port definition for camera preview output port 70");
    dump_port(ctx.camera, 70, OMX_TRUE);
    say("Default port definition for camera video output port 71");
    dump_port(ctx.camera, 71, OMX_TRUE);

		OMX_TIME_CONFIG_CLOCKSTATETYPE cstate;
		OMX_INIT_STRUCTURE(cstate);
		cstate.eState = OMX_TIME_ClockStateRunning;
		cstate.nWaitMask = 1;
    if((r = OMX_SetConfig(ctx.clock, OMX_IndexConfigTimeClockState, &cstate)) != OMX_ErrorNone) {
        omx_die(r, "Failed to request camera device number parameter change callback for camera");
    }

    // Request a callback to be made when OMX_IndexParamCameraDeviceNumber is
    // changed signaling that the camera device is ready for use.
    OMX_CONFIG_REQUESTCALLBACKTYPE cbtype;
    OMX_INIT_STRUCTURE(cbtype);
    cbtype.nPortIndex = OMX_ALL;
    cbtype.nIndex     = OMX_IndexParamCameraDeviceNumber;
    cbtype.bEnable    = OMX_TRUE;
    if((r = OMX_SetConfig(ctx.camera, OMX_IndexConfigRequestCallback, &cbtype)) != OMX_ErrorNone) {
        omx_die(r, "Failed to request camera device number parameter change callback for camera");
    }
    // Set device number, this triggers the callback configured just above
    OMX_PARAM_U32TYPE device;
    OMX_INIT_STRUCTURE(device);
    device.nPortIndex = OMX_ALL;
    device.nU32 = CAM_DEVICE_NUMBER;
    if((r = OMX_SetParameter(ctx.camera, OMX_IndexParamCameraDeviceNumber, &device)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set camera parameter device number");
    }
    // Configure video format emitted by camera preview output port
    OMX_PARAM_PORTDEFINITIONTYPE camera_portdef;
    OMX_INIT_STRUCTURE(camera_portdef);
    camera_portdef.nPortIndex = 70;
    if((r = OMX_GetParameter(ctx.camera, OMX_IndexParamPortDefinition, &camera_portdef)) != OMX_ErrorNone) {
        omx_die(r, "Failed to get port definition for camera preview output port 70");
    }
    camera_portdef.format.video.nFrameWidth  = state->screen_width;
    camera_portdef.format.video.nFrameHeight = state->screen_height;
    camera_portdef.format.video.xFramerate   = VIDEO_FRAMERATE << 16;
    // Stolen from gstomxvideodec.c of gst-omx
    camera_portdef.format.video.nStride      = (camera_portdef.format.video.nFrameWidth + camera_portdef.nBufferAlignment - 1) & (~(camera_portdef.nBufferAlignment - 1));
    camera_portdef.format.video.eColorFormat = OMX_COLOR_FormatYUV420PackedPlanar;
    if((r = OMX_SetParameter(ctx.camera, OMX_IndexParamPortDefinition, &camera_portdef)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set port definition for camera preview output port 70");
    }
    // Configure video format emitted by camera video output port
    // Use configuration from camera preview output as basis for
    // camera video output configuration
    OMX_INIT_STRUCTURE(camera_portdef);
    camera_portdef.nPortIndex = 70;
    if((r = OMX_GetParameter(ctx.camera, OMX_IndexParamPortDefinition, &camera_portdef)) != OMX_ErrorNone) {
        omx_die(r, "Failed to get port definition for camera preview output port 70");
    }
    camera_portdef.nPortIndex = 71;
    if((r = OMX_SetParameter(ctx.camera, OMX_IndexParamPortDefinition, &camera_portdef)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set port definition for camera video output port 71");
    }
    // Configure frame rate
    OMX_CONFIG_FRAMERATETYPE framerate;
    OMX_INIT_STRUCTURE(framerate);
    framerate.nPortIndex = 70;
    framerate.xEncodeFramerate = camera_portdef.format.video.xFramerate;
    if((r = OMX_SetConfig(ctx.camera, OMX_IndexConfigVideoFramerate, &framerate)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set framerate configuration for camera preview output port 70");
    }
    framerate.nPortIndex = 71;
    if((r = OMX_SetConfig(ctx.camera, OMX_IndexConfigVideoFramerate, &framerate)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set framerate configuration for camera video output port 71");
    }
    // Configure sharpness
    OMX_CONFIG_SHARPNESSTYPE sharpness;
    OMX_INIT_STRUCTURE(sharpness);
    sharpness.nPortIndex = OMX_ALL;
    sharpness.nSharpness = CAM_SHARPNESS;
    if((r = OMX_SetConfig(ctx.camera, OMX_IndexConfigCommonSharpness, &sharpness)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set camera sharpness configuration");
    }
    // Configure contrast
    OMX_CONFIG_CONTRASTTYPE contrast;
    OMX_INIT_STRUCTURE(contrast);
    contrast.nPortIndex = OMX_ALL;
    contrast.nContrast = CAM_CONTRAST;
    if((r = OMX_SetConfig(ctx.camera, OMX_IndexConfigCommonContrast, &contrast)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set camera contrast configuration");
    }
    // Configure saturation
    OMX_CONFIG_SATURATIONTYPE saturation;
    OMX_INIT_STRUCTURE(saturation);
    saturation.nPortIndex = OMX_ALL;
    saturation.nSaturation = CAM_SATURATION;
    if((r = OMX_SetConfig(ctx.camera, OMX_IndexConfigCommonSaturation, &saturation)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set camera saturation configuration");
    }
    // Configure brightness
    OMX_CONFIG_BRIGHTNESSTYPE brightness;
    OMX_INIT_STRUCTURE(brightness);
    brightness.nPortIndex = OMX_ALL;
    brightness.nBrightness = CAM_BRIGHTNESS;
    if((r = OMX_SetConfig(ctx.camera, OMX_IndexConfigCommonBrightness, &brightness)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set camera brightness configuration");
    }
    // Configure exposure value
    OMX_CONFIG_EXPOSUREVALUETYPE exposure_value;
    OMX_INIT_STRUCTURE(exposure_value);
    exposure_value.nPortIndex = OMX_ALL;
    exposure_value.xEVCompensation = CAM_EXPOSURE_VALUE_COMPENSTAION;
    exposure_value.bAutoSensitivity = CAM_EXPOSURE_AUTO_SENSITIVITY;
		exposure_value.bAutoShutterSpeed = OMX_TRUE;
//		exposure_value.nShutterSpeedMsec = 10;
    exposure_value.nSensitivity = CAM_EXPOSURE_ISO_SENSITIVITY;
		exposure_value.eMetering = OMX_MeteringModeAverage;
    if((r = OMX_SetConfig(ctx.camera, OMX_IndexConfigCommonExposureValue, &exposure_value)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set camera exposure value configuration");
    }
	  OMX_CONFIG_EXPOSURECONTROLTYPE exposure;
 	  OMX_INIT_STRUCTURE(exposure);
	  exposure.nPortIndex = OMX_ALL;
	  exposure.eExposureControl = OMX_ExposureControlAuto;
 	  OMX_SetConfig(ctx.camera, OMX_IndexConfigCommonExposure, &exposure);
    // Configure frame frame stabilisation
    OMX_CONFIG_FRAMESTABTYPE frame_stabilisation_control;
    OMX_INIT_STRUCTURE(frame_stabilisation_control);
    frame_stabilisation_control.nPortIndex = OMX_ALL;
    frame_stabilisation_control.bStab = CAM_FRAME_STABILISATION;
    if((r = OMX_SetConfig(ctx.camera, OMX_IndexConfigCommonFrameStabilisation, &frame_stabilisation_control)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set camera frame frame stabilisation control configuration");
    }
    // Configure frame white balance control
/*    OMX_CONFIG_LIGHTNESSTYPE lightness_control;
    OMX_INIT_STRUCTURE(lightness_control);
    lightness_control.nPortIndex = OMX_ALL;
    lightness_control.nLightness = 0;
    if((r = OMX_SetConfig(ctx.camera, OMX_IndexConfigCommonLightness, &lightness_control)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set camera frame white balance control configuration");
    }*/
    // Configure frame white balance control
    OMX_CONFIG_WHITEBALCONTROLTYPE white_balance_control;
    OMX_INIT_STRUCTURE(white_balance_control);
    white_balance_control.nPortIndex = OMX_ALL;
    white_balance_control.eWhiteBalControl = CAM_WHITE_BALANCE_CONTROL;
    if((r = OMX_SetConfig(ctx.camera, OMX_IndexConfigCommonWhiteBalance, &white_balance_control)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set camera frame white balance control configuration");
    }
    // Configure image filter
    OMX_CONFIG_IMAGEFILTERTYPE image_filter;
    OMX_INIT_STRUCTURE(image_filter);
    image_filter.nPortIndex = OMX_ALL;
    image_filter.eImageFilter = CAM_IMAGE_FILTER;
    if((r = OMX_SetConfig(ctx.camera, OMX_IndexConfigCommonImageFilter, &image_filter)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set camera image filter configuration");
    }
  /* Set colour effect */
  OMX_CONFIG_COLORENHANCEMENTTYPE colour;
  OMX_INIT_STRUCTURE(colour);
  colour.nPortIndex = OMX_ALL;
  colour.bColorEnhancement = OMX_FALSE;
  colour.nCustomizedU = 128;
  colour.nCustomizedV = 128;
  OMX_SetConfig(ctx.camera, OMX_IndexConfigCommonColorEnhancement, &colour);

    // Configure mirror
    OMX_MIRRORTYPE eMirror = OMX_MirrorNone;
    if(CAM_FLIP_HORIZONTAL && !CAM_FLIP_VERTICAL) {
        eMirror = OMX_MirrorHorizontal;
    } else if(!CAM_FLIP_HORIZONTAL && CAM_FLIP_VERTICAL) {
        eMirror = OMX_MirrorVertical;
    } else if(CAM_FLIP_HORIZONTAL && CAM_FLIP_VERTICAL) {
        eMirror = OMX_MirrorBoth;
    }
    OMX_CONFIG_MIRRORTYPE mirror;
    OMX_INIT_STRUCTURE(mirror);
    mirror.nPortIndex = 71;
    mirror.eMirror = eMirror;
    if((r = OMX_SetConfig(ctx.camera, OMX_IndexConfigCommonMirror, &mirror)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set mirror configuration for camera video output port 71");
    }

    // Ensure camera is ready
    while(!ctx.camera_ready) {
        usleep(10000);
    }

    say("Configuring render...");

    say("Default port definition for render input port 90");
    dump_port(ctx.render, 220, OMX_TRUE);

    // Render input port definition is done automatically upon tunneling


    say("Configuring null sink...");

    say("Default port definition for null sink input port 240");
    dump_port(ctx.null_sink, 240, OMX_TRUE);

    // Null sink input port definition is done automatically upon tunneling

    // Tunnel camera preview output port and null sink input port
    say("Setting up tunnel from camera preview output port 70 to null sink input port 240...");
    if((r = OMX_SetupTunnel(ctx.clock, 80, ctx.camera, 73)) != OMX_ErrorNone) {
        omx_die(r, "Failed to setup tunnel between camera preview output port 70 and null sink input port 240");
    }
    // Tunnel camera preview output port and null sink input port
    say("Setting up tunnel from camera preview output port 70 to null sink input port 240...");
    if((r = OMX_SetupTunnel(ctx.camera, 70, ctx.null_sink, 240)) != OMX_ErrorNone) {
        omx_die(r, "Failed to setup tunnel between camera preview output port 70 and null sink input port 240");
    }

    // Tunnel camera video output port and render input port
    say("Setting up tunnel from camera video output port 71 to render input port 220...");
    if((r = OMX_SetupTunnel(ctx.camera, 71, ctx.render, 220)) != OMX_ErrorNone) {
        omx_die(r, "Failed to setup tunnel between camera video output port 71 and render input port 90");
    }

    // Switch components to idle state
    say("Switching state of the camera component to idle...");
    if((r = OMX_SendCommand(ctx.clock, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the camera component to idle");
    }
    block_until_state_changed(ctx.clock, OMX_StateIdle);    say("Switching state of the camera component to idle...");
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the camera component to idle");
    }
    block_until_state_changed(ctx.camera, OMX_StateIdle);
    say("Switching state of the render component to idle...");
    if((r = OMX_SendCommand(ctx.render, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the render component to idle");
    }
    block_until_state_changed(ctx.render, OMX_StateIdle);
    say("Switching state of the null sink component to idle...");
    if((r = OMX_SendCommand(ctx.null_sink, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the null sink component to idle");
    }
    block_until_state_changed(ctx.null_sink, OMX_StateIdle);

    // Enable ports
    say("Enabling ports...");
    if((r = OMX_SendCommand(ctx.clock, OMX_CommandPortEnable, 80, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to enable camera input port 73");
    }
    block_until_port_changed(ctx.clock, 80, OMX_TRUE);    if((r = OMX_SendCommand(ctx.camera, OMX_CommandPortEnable, 73, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to enable camera input port 73");
    }
    block_until_port_changed(ctx.camera, 73, OMX_TRUE);
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandPortEnable, 70, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to enable camera preview output port 70");
    }
    block_until_port_changed(ctx.camera, 70, OMX_TRUE);
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandPortEnable, 71, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to enable camera video output port 71");
    }
    block_until_port_changed(ctx.camera, 71, OMX_TRUE);
    if((r = OMX_SendCommand(ctx.render, OMX_CommandPortEnable, 220, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to enable render input port 220");
    }
    block_until_port_changed(ctx.render, 220, OMX_TRUE);
   if((r = OMX_SendCommand(ctx.render, OMX_CommandPortEnable, 221, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to enable render input port 221");
    }
    block_until_port_changed(ctx.render, 220, OMX_TRUE);
    if((r = OMX_SendCommand(ctx.null_sink, OMX_CommandPortEnable, 240, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to enable null sink input port 240");
    }
    block_until_port_changed(ctx.null_sink, 240, OMX_TRUE);

    // Allocate camera input buffer, buffers for tunneled
    // ports are allocated internally by OMX

		if((r = OMX_UseEGLImage(ctx.render, &ctx.eglBuffer, 221, NULL, ctx.eglImage)) != OMX_ErrorNone)
		{
        omx_die(r, "Failed to use eglimage");
		}

    // Switch state of the components prior to starting
    // the video capture and encoding loop
    say("Switching state of the camera component to executing...");
    if((r = OMX_SendCommand(ctx.clock, OMX_CommandStateSet, OMX_StateExecuting, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the camera component to executing");
    }    say("Switching state of the camera component to executing...");
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandStateSet, OMX_StateExecuting, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the camera component to executing");
    }
    block_until_state_changed(ctx.camera, OMX_StateExecuting);
    say("Switching state of the render component to executing...");
    if((r = OMX_SendCommand(ctx.render, OMX_CommandStateSet, OMX_StateExecuting, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the render component to executing");
    }
    block_until_state_changed(ctx.render, OMX_StateExecuting);
    say("Switching state of the null sink component to executing...");
    if((r = OMX_SendCommand(ctx.null_sink, OMX_CommandStateSet, OMX_StateExecuting, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the null sink component to executing");
    }
    block_until_state_changed(ctx.null_sink, OMX_StateExecuting);

    // Start capturing video with the camera
    say("Switching on capture on camera video output port 71...");
    OMX_CONFIG_PORTBOOLEANTYPE capture;
    OMX_INIT_STRUCTURE(capture);
    capture.nPortIndex = 71;
    capture.bEnabled = OMX_TRUE;
    if((r = OMX_SetParameter(ctx.camera, OMX_IndexConfigPortCapturing, &capture)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch on capture on camera video output port 71");
    }

    say("Configured port definition for camera input port 73");
    dump_port(ctx.camera, 73, OMX_FALSE);
    say("Configured port definition for camera preview output port 70");
    dump_port(ctx.camera, 70, OMX_FALSE);
    say("Configured port definition for camera video output port 71");
    dump_port(ctx.camera, 71, OMX_FALSE);
    say("Configured port definition for render input port 90");
    dump_port(ctx.render, 220, OMX_FALSE);
    say("Configured port definition for null sink input port 240");
    dump_port(ctx.null_sink, 240, OMX_FALSE);

    say("Enter capture and playback loop, press Ctrl-C to quit...");

		if((r = OMX_FillThisBuffer(ctx.render, ctx.eglBuffer)) != OMX_ErrorNone)
		{
      omx_die(r, "Failed to fill buffer");
		}

    signal(SIGINT,  signal_handler);
    signal(SIGTERM, signal_handler);
    signal(SIGQUIT, signal_handler);

    while(!want_quit) {
        // Would be better to use signaling here but hey this works too
        usleep(1000);
    }
    say("Cleaning up...");

    // Restore signal handlers
    signal(SIGINT,  SIG_DFL);
    signal(SIGTERM, SIG_DFL);
    signal(SIGQUIT, SIG_DFL);

    // Stop capturing video with the camera
    OMX_INIT_STRUCTURE(capture);
    capture.nPortIndex = 71;
    capture.bEnabled = OMX_FALSE;
    if((r = OMX_SetParameter(ctx.camera, OMX_IndexConfigPortCapturing, &capture)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch off capture on camera video output port 71");
    }

    // Flush the buffers on each component
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandFlush, 73, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to flush buffers of camera input port 73");
    }
    block_until_flushed(&ctx);
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandFlush, 70, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to flush buffers of camera preview output port 70");
    }
    block_until_flushed(&ctx);
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandFlush, 71, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to flush buffers of camera video output port 71");
    }
    block_until_flushed(&ctx);
    if((r = OMX_SendCommand(ctx.render, OMX_CommandFlush, 220, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to flush buffers of render input port 220");
    }
    block_until_flushed(&ctx);
    if((r = OMX_SendCommand(ctx.null_sink, OMX_CommandFlush, 240, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to flush buffers of null sink input port 240");
    }
    block_until_flushed(&ctx);

    // Disable all the ports
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandPortDisable, 73, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to disable camera input port 73");
    }
    block_until_port_changed(ctx.camera, 73, OMX_FALSE);
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandPortDisable, 70, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to disable camera preview output port 70");
    }
    block_until_port_changed(ctx.camera, 70, OMX_FALSE);
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandPortDisable, 71, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to disable camera video output port 71");
    }
    block_until_port_changed(ctx.camera, 71, OMX_FALSE);
    if((r = OMX_SendCommand(ctx.render, OMX_CommandPortDisable, 220, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to disable render input port 90");
    }
    if((r = OMX_SendCommand(ctx.null_sink, OMX_CommandPortDisable, 240, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to disable null sink input port 240");
    }
    block_until_port_changed(ctx.null_sink, 240, OMX_FALSE);

    // Free all the buffers
    if((r = OMX_FreeBuffer(ctx.camera, 73, ctx.camera_ppBuffer_in)) != OMX_ErrorNone) {
        omx_die(r, "Failed to free buffer for camera input port 73");
    }

    // Transition all the components to idle and then to loaded states
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the camera component to idle");
    }
    block_until_state_changed(ctx.camera, OMX_StateIdle);
    if((r = OMX_SendCommand(ctx.render, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the render component to idle");
    }
    block_until_state_changed(ctx.render, OMX_StateIdle);
    if((r = OMX_SendCommand(ctx.null_sink, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the null sink component to idle");
    }
    block_until_state_changed(ctx.null_sink, OMX_StateIdle);
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandStateSet, OMX_StateLoaded, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the camera component to loaded");
    }
    block_until_state_changed(ctx.camera, OMX_StateLoaded);
    if((r = OMX_SendCommand(ctx.render, OMX_CommandStateSet, OMX_StateLoaded, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the render component to loaded");
    }
    block_until_state_changed(ctx.render, OMX_StateLoaded);
    if((r = OMX_SendCommand(ctx.null_sink, OMX_CommandStateSet, OMX_StateLoaded, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the null sink component to loaded");
    }
    block_until_state_changed(ctx.null_sink, OMX_StateLoaded);

    // Free the component handles
    if((r = OMX_FreeHandle(ctx.camera)) != OMX_ErrorNone) {
        omx_die(r, "Failed to free camera component handle");
    }
    if((r = OMX_FreeHandle(ctx.render)) != OMX_ErrorNone) {
        omx_die(r, "Failed to free render component handle");
    }
    if((r = OMX_FreeHandle(ctx.null_sink)) != OMX_ErrorNone) {
        omx_die(r, "Failed to free null sink component handle");
    }

    // Exit
    vcos_semaphore_delete(&ctx.handler_lock);
    if((r = OMX_Deinit()) != OMX_ErrorNone) {
        omx_die(r, "OMX de-initalization failed");
    }

    say("Exit!");

    return 0;
}
static void handle_msg(int fd, struct msg* m)
{
    switch (m->type) {
    case MSG_GET_HANDLE: {
        struct comp* c = (struct comp*) malloc(sizeof(struct comp));
        fprintf(stderr, "ILSRV: GetHandle '%s'\n", m->cmd.get_handle.name);
        m->result = OMX_GetHandle(&c->real_handle, m->cmd.get_handle.name, c, &callbacks);
        m->cmd.get_handle.out_srv_handle = (int) c;
        c->client_handle = m->cmd.get_handle.in_client_handle;
        c->client_fd     = fd;
        c->state         = OMX_StateLoaded;
        strncpy(c->name, m->cmd.get_handle.name, sizeof(c->name));
        c->name[sizeof(c->name)-1]=0;
        add_component(c);
        fprintf(stderr, "ILSRV: %08X [%20s] --> %s%s\n", c->real_handle, last_part(c->name), m->result == OMX_ErrorNone ? "" : "ERROR ", adm_log_err2str(m->result));
        return;
    }

    case MSG_SET_PARAM:{
        struct comp* c = (struct comp*) m->cmd.param.srv_handle;
        verify_component(c);
        fprintf(stderr, "ILSRV: %08X [%20s] SetParam %s\n", c->real_handle, last_part(c->name), adm_log_index2str(m->cmd.param.index));
        m->result = OMX_SetParameter(c->real_handle, (OMX_INDEXTYPE) m->cmd.param.index, m->cmd.param.buf); // TODO: Protect
        fprintf(stderr, "ILSRV: --> %s %s\n", m->result == OMX_ErrorNone ? "" : "ERROR ", adm_log_err2str(m->result));
        return;
    }
    case MSG_GET_PARAM:{
        struct comp* c = (struct comp*) m->cmd.param.srv_handle;
        verify_component(c);
        fprintf(stderr, "ILSRV: %08X [%20s] GetParam %s\n", c->real_handle, last_part(c->name), adm_log_index2str(m->cmd.param.index));
        m->result = OMX_GetParameter(c->real_handle, (OMX_INDEXTYPE)m->cmd.param.index, m->cmd.param.buf); // TODO: Protect
        fprintf(stderr, "ILSRV: --> %s %s\n", m->result == OMX_ErrorNone ? "" : "ERROR ", adm_log_err2str(m->result));
        return;
    }

    case MSG_GET_CONFIG:{
        struct comp* c = (struct comp*) m->cmd.param.srv_handle;
        verify_component(c);
        fprintf(stderr, "ILSRV: %08X [%20s] GetConfig %s\n", c->real_handle, last_part(c->name), adm_log_index2str(m->cmd.param.index));
        m->result = OMX_GetConfig(c->real_handle, (OMX_INDEXTYPE)m->cmd.param.index, m->cmd.param.buf); // TODO: Protect
        fprintf(stderr, "ILSRV: --> %s %s\n", m->result == OMX_ErrorNone ? "" : "ERROR ", adm_log_err2str(m->result));
        return;
    }

    case MSG_SET_CONFIG: {
        struct comp* c = (struct comp*) m->cmd.param.srv_handle;
        verify_component(c);
        fprintf(stderr, "ILSRV: %08X [%20s] SetConfig %s\n", c->real_handle, last_part(c->name), adm_log_index2str(m->cmd.param.index));
        m->result = OMX_SetConfig(c->real_handle, (OMX_INDEXTYPE)m->cmd.param.index, m->cmd.param.buf); // TODO: Protect
        fprintf(stderr, "ILSRV: --> %s %s\n", m->result == OMX_ErrorNone ? "" : "ERROR ", adm_log_err2str(m->result));
        return;
    }

    case MSG_FREE_HANDLE: {
        struct comp* c = (struct comp*) m->cmd.free_handle.srv_handle;
        verify_component(c);
        if (c->state != OMX_StateLoaded) {
            fprintf(stderr, "ILSRV: FreeHandle called for %X which is in wrong state (%s)\m", c->real_handle, adm_log_state2str(c->state));
            error_found();
        }
        fprintf(stderr, "ILSRV: %08X [%20s] Freehandle (internal=%X)\n", c->real_handle, last_part(c->name), c);
        m->result = OMX_FreeHandle(c->real_handle);
        fprintf(stderr, "ILSRV: --> %s %s\n", m->result == OMX_ErrorNone ? "" : "ERROR ", adm_log_err2str(m->result));
        del_component(c);
        memset(c, 0xFE, sizeof(*c));
        free(c);
        return;
    }

    case MSG_SEND_COMMAND: {
        struct comp* c = (struct comp*) m->cmd.free_handle.srv_handle;
        verify_component(c);
        if (m->cmd.command.cmd == OMX_CommandStateSet) {
            fprintf(stderr, "ILSRV: %08X [%20s] SendCommand StateSet %s\n", c->real_handle, last_part(c->name), adm_log_state2str((OMX_STATETYPE) m->cmd.command.nParam1));
        } else {
            fprintf(stderr, "ILSRV: %08X [%20s] SendCommand StateSet %s 0x%X\n", c->real_handle, last_part(c->name), adm_log_cmd2str(m->cmd.command.cmd), m->cmd.command.nParam1);
        }

        m->result = OMX_SendCommand(c->real_handle, m->cmd.command.cmd, m->cmd.command.nParam1, 0);
        fprintf(stderr, "ILSRV: --> %s %s\n", m->result == OMX_ErrorNone ? "" : "ERROR ", adm_log_err2str(m->result));
        return;
    }

    case MSG_SETUP_TUNNEL: {
        struct comp* c_in = (struct comp*) m->cmd.tunnel.srv_handle_in;
        struct comp* c_out = (struct comp*) m->cmd.tunnel.srv_handle_out;
        verify_component(c_in);
        verify_component(c_out);

        fprintf(stderr, "ILSRV: SetupTunnel %08X [%20s].%d --> %08X [%20s].%d\n", c_out->real_handle, last_part(c_out->name), m->cmd.tunnel.port_out, c_in->real_handle, last_part(c_in->name), m->cmd.tunnel.port_in);
        m->result = OMX_SetupTunnel(c_out->real_handle, m->cmd.tunnel.port_out, c_in->real_handle, m->cmd.tunnel.port_in);
        fprintf(stderr, "ILSRV: --> %s %s\n", m->result == OMX_ErrorNone ? "" : "ERROR ", adm_log_err2str(m->result));
        return;
    }

    case MSG_GET_STATE: {
        struct comp* c = (struct comp*) m->cmd.get_state.in_srv_handle;
        verify_component(c);
        fprintf(stderr, "ILSRV: %08X [%20s] GetState\n", c->real_handle, last_part(c->name));
        m->result = OMX_GetState(c->real_handle, &m->cmd.get_state.out_state);
        fprintf(stderr, "ILSRV: --> %s %s %s\n", m->result == OMX_ErrorNone ? "" : "ERROR ", adm_log_err2str(m->result), adm_log_state2str(m->cmd.get_state.out_state));
        return;
    }

    case MSG_ALLOC_BUFFER: {
        struct comp* c = (struct comp*) m->cmd.alloc_buffer.in_srv_handle;
        verify_component(c);

        OMX_BUFFERHEADERTYPE* bufhdr;
        fprintf(stderr, "ILSRV: %08X [%20s] AllocBuf port=%d size=%d\n", c->real_handle, last_part(c->name), m->cmd.alloc_buffer.port, m->cmd.alloc_buffer.size);
        m->result = OMX_AllocateBuffer(c->real_handle, &bufhdr, m->cmd.alloc_buffer.port,
                     (void*) m->cmd.alloc_buffer.in_client_buf_hdr, m->cmd.alloc_buffer.size);

        if (m->result == OMX_ErrorNone) {
            memcpy(&m->cmd.alloc_buffer.out_buf_hdr, bufhdr, sizeof(OMX_BUFFERHEADERTYPE));
            m->cmd.alloc_buffer.out_srv_buf_hdr = (int) bufhdr;
            add_bufhdr(bufhdr);
        }
        fprintf(stderr, "ILSRV: --> %s %s\n", m->result == OMX_ErrorNone ? "" : "ERROR ", adm_log_err2str(m->result));
        return;
    }

    case MSG_EMPTY_BUFFER: {
        struct comp* c = (struct comp*) m->cmd.empty_buffer.in_srv_handle;
        verify_component(c);

        OMX_BUFFERHEADERTYPE* client_bufhdr = (OMX_BUFFERHEADERTYPE*) &m->cmd.empty_buffer.in_buf_hdr;
        OMX_BUFFERHEADERTYPE* bufhdr = (OMX_BUFFERHEADERTYPE*) client_bufhdr->pPlatformPrivate;

        verify_bufhdr(bufhdr);

        if (bufhdr->nAllocLen <= sizeof(m->cmd.empty_buffer.in_buf)) {
            bufhdr->nOffset    = client_bufhdr->nOffset;
            bufhdr->nTimeStamp = client_bufhdr->nTimeStamp;
            bufhdr->nFilledLen = client_bufhdr->nFilledLen;
            bufhdr->nFlags     = client_bufhdr->nFlags;

            memcpy(bufhdr->pBuffer, &m->cmd.empty_buffer.in_buf, bufhdr->nAllocLen);
            fprintf(stderr, "ILSRV: %08X [%20s] EmptyBuffer port=%d size=%d\n", c->real_handle, last_part(c->name), bufhdr->nInputPortIndex, bufhdr->nAllocLen);
            m->result = OMX_EmptyThisBuffer(c->real_handle, bufhdr);
            fprintf(stderr, "ILSRV: --> %s %s\n", m->result == OMX_ErrorNone ? "" : "ERROR ", adm_log_err2str(m->result));
        } else {
            assert(0);
        }

        return;
    }

    case MSG_FILL_BUFFER: {
        struct comp* c = (struct comp*) m->cmd.empty_buffer.in_srv_handle;
        verify_component(c);

        OMX_BUFFERHEADERTYPE* client_bufhdr = (OMX_BUFFERHEADERTYPE*) &m->cmd.fill_buffer.in_buf_hdr;
        OMX_BUFFERHEADERTYPE* bufhdr = (OMX_BUFFERHEADERTYPE*) client_bufhdr->pPlatformPrivate;

        verify_bufhdr(bufhdr);

        fprintf(stderr, "ILSRV: %08X [%20s] FillBuffer port=%d size=%d\n", c->real_handle, last_part(c->name), bufhdr->nOutputPortIndex, bufhdr->nAllocLen);
        m->result = OMX_FillThisBuffer(c->real_handle, bufhdr);
        fprintf(stderr, "ILSRV: --> %s %s\n", m->result == OMX_ErrorNone ? "" : "ERROR ", adm_log_err2str(m->result));

        return;
    }

    case MSG_FREE_BUFFER: {
        struct comp* c = (struct comp*) m->cmd.empty_buffer.in_srv_handle;
        verify_component(c);

        OMX_BUFFERHEADERTYPE* bufhdr = (OMX_BUFFERHEADERTYPE*) m->cmd.free_buffer.in_srv_buf_hdr;
        verify_bufhdr(bufhdr);

        del_bufhdr(bufhdr);
        fprintf(stderr, "ILSRV: %08X [%20s] FreeBuffer\n", c->real_handle, last_part(c->name));
        m->result = OMX_FreeBuffer(c->real_handle, m->cmd.free_buffer.in_port, bufhdr);
        fprintf(stderr, "ILSRV: --> %s %s\n", m->result == OMX_ErrorNone ? "" : "ERROR ", adm_log_err2str(m->result));
        return;
    }

    default:
       fprintf(stderr, "ILSRV: Unhandled request received\n");
       m->result = OMX_ErrorNotImplemented;
       error_found();
       return;
    }
Пример #20
0
Component::~Component()
{
    
    ofLogVerbose(__func__) << getName();
    OMX_ERRORTYPE error;

    if(handle)
    {
        for (size_t i = 0; i < inputBuffers.size(); i++)
        {
            error = OMX_FreeBuffer(handle, inputPort, inputBuffers[i]);
            OMX_TRACE(error);
        }
       
    }
    
    while (!inputBuffersAvailable.empty())
    {
        inputBuffersAvailable.pop();
    }
    inputBuffers.clear();
    
    //if(componentName != "OMX.broadcom.video_decode")
    //{
        
    if (doFreeHandle) 
    {
        
        error = OMX_FreeHandle(handle);
        OMX_TRACE(error); 
        ofLogVerbose(__func__) << componentName << " FREED";
    }else
    {
        stringstream info;
        
        OMX_STATETYPE currentState;
        OMX_GetState(handle, &currentState);
        
        
        OMX_PARAM_U32TYPE extra_buffers;
        OMX_INIT_STRUCTURE(extra_buffers);
        
        error = getParameter(OMX_IndexParamBrcmExtraBuffers, &extra_buffers);
        OMX_TRACE(error);
        info << "currentState: " << GetOMXStateString(currentState) << endl;
        info << "PRE extra_buffers.nU32: " << (int)extra_buffers.nU32 << endl;
       
        extra_buffers.nU32 = 0;
        error = setParameter(OMX_IndexParamBrcmExtraBuffers, &extra_buffers);
        OMX_TRACE(error);
        
        error = getParameter(OMX_IndexParamBrcmExtraBuffers, &extra_buffers);
        info << "POST extra_buffers.nU32: " << (int)extra_buffers.nU32 << endl;
        
        flushAll();
        
        disableAllPorts();
        ofLogVerbose(__func__) << info.str();
        //error = OMX_FreeHandle(handle);
        //OMX_TRACE(error); 
        //ofLogVerbose(__func__) << info.str() << " " << componentName << " FREED";

    }

    //}
    
    handle = NULL;
    
    
    //error =  waitForCommand(OMX_CommandPortDisable, inputPort);
    //OMX_TRACE(error);
    
  
 
	pthread_mutex_destroy(&m_omx_input_mutex);
	pthread_mutex_destroy(&m_omx_output_mutex);
	pthread_mutex_destroy(&event_mutex);
	pthread_mutex_destroy(&eos_mutex);
	pthread_cond_destroy(&m_input_buffer_cond);
	pthread_cond_destroy(&m_output_buffer_cond);
	pthread_cond_destroy(&m_omx_event_cond);

	pthread_mutex_destroy(&m_lock);
	sem_destroy(&m_omx_fill_buffer_done);

}
void encoder_close()
{
	OMX_ERRORTYPE r;
	//say("Cleaning up...");

    // Stop capturing video with the camera
    OMX_CONFIG_PORTBOOLEANTYPE capture;
    OMX_INIT_STRUCTURE(capture);
    capture.nPortIndex = 71;
    capture.bEnabled = OMX_FALSE;
    if((r = OMX_SetParameter(ctx.camera, OMX_IndexConfigPortCapturing, &capture)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch off capture on camera video output port 71");
    }
	
    // Return the last full buffer back to the encoder component
    ctx.encoder_ppBuffer_out->nFlags = OMX_BUFFERFLAG_EOS;
    if((r = OMX_FillThisBuffer(ctx.encoder, ctx.encoder_ppBuffer_out)) != OMX_ErrorNone) {
        omx_die(r, "Failed to request filling of the output buffer on encoder output port 201");
    }
	//say("Cleaning up1...");

    // Disable all the ports
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandPortDisable, 73, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to disable camera input port 73");
    }
    //block_until_port_changed(ctx.camera, 73, OMX_FALSE);
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandPortDisable, 70, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to disable camera preview output port 70");
    }
    //block_until_port_changed(ctx.camera, 70, OMX_FALSE);
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandPortDisable, 71, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to disable camera video output port 71");
    }
    //block_until_port_changed(ctx.camera, 71, OMX_FALSE);
    if((r = OMX_SendCommand(ctx.encoder, OMX_CommandPortDisable, 200, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to disable encoder input port 200");
    }
    //block_until_port_changed(ctx.encoder, 200, OMX_FALSE);
    if((r = OMX_SendCommand(ctx.encoder, OMX_CommandPortDisable, 201, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to disable encoder output port 201");
    }
    //block_until_port_changed(ctx.encoder, 201, OMX_FALSE);
    if((r = OMX_SendCommand(ctx.null_sink, OMX_CommandPortDisable, 240, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to disable null sink input port 240");
    }
    //block_until_port_changed(ctx.null_sink, 240, OMX_FALSE);
	//say("Cleaning up3...");
    // Free all the buffers
    if((r = OMX_FreeBuffer(ctx.camera, 73, ctx.camera_ppBuffer_in)) != OMX_ErrorNone) {
        omx_die(r, "Failed to free buffer for camera input port 73");
    }
    if((r = OMX_FreeBuffer(ctx.encoder, 201, ctx.encoder_ppBuffer_out)) != OMX_ErrorNone) {
        omx_die(r, "Failed to free buffer for encoder output port 201");
    }
	//say("Cleaning up4...");
    // Transition all the components to idle and then to loaded states
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the camera component to idle");
    }
    //block_until_state_changed(ctx.camera, OMX_StateIdle);
    if((r = OMX_SendCommand(ctx.encoder, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the encoder component to idle");
    }
    //block_until_state_changed(ctx.encoder, OMX_StateIdle);
    if((r = OMX_SendCommand(ctx.null_sink, OMX_CommandStateSet, OMX_StateIdle, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the null sink component to idle");
    }
    //block_until_state_changed(ctx.null_sink, OMX_StateIdle);
    if((r = OMX_SendCommand(ctx.camera, OMX_CommandStateSet, OMX_StateLoaded, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the camera component to loaded");
    }
    //block_until_state_changed(ctx.camera, OMX_StateLoaded);
    if((r = OMX_SendCommand(ctx.encoder, OMX_CommandStateSet, OMX_StateLoaded, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the encoder component to loaded");
    }
    //block_until_state_changed(ctx.encoder, OMX_StateLoaded);
    if((r = OMX_SendCommand(ctx.null_sink, OMX_CommandStateSet, OMX_StateLoaded, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the null sink component to loaded");
    }
    //block_until_state_changed(ctx.null_sink, OMX_StateLoaded);

    // Free the component handles
    if((r = OMX_FreeHandle(ctx.camera)) != OMX_ErrorNone) {
        omx_die(r, "Failed to free camera component handle");
    }
    if((r = OMX_FreeHandle(ctx.encoder)) != OMX_ErrorNone) {
        omx_die(r, "Failed to free encoder component handle");
    }
    if((r = OMX_FreeHandle(ctx.null_sink)) != OMX_ErrorNone) {
        omx_die(r, "Failed to free null sink component handle");
    }

    vcos_semaphore_delete(&ctx.handler_lock);
    if((r = OMX_Deinit()) != OMX_ErrorNone) {
        omx_die(r, "OMX de-initalization failed");
    }
}
Пример #22
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;
}
    OMX_ERRORTYPE OMX_CONF_BufferTest(OMX_IN OMX_STRING cComponentName)
    {
        OMX_ERRORTYPE eError = OMX_ErrorNone;
        OMX_ERRORTYPE eCleanupError = OMX_ErrorNone;
        TEST_CTXTYPE ctx;
        TEST_CTXTYPE *pCtx;
        OMX_HANDLETYPE hComp  = 0x0;
        OMX_CALLBACKTYPE oCallbacks;
        OMX_HANDLETYPE hWrappedComp = 0x0;
        OMX_CALLBACKTYPE *pWrappedCallbacks;
        OMX_PTR pWrappedAppData;
        OMX_BOOL bTimeout;
        TEST_PORTTYPE *pPort;
        OMX_U32 i;
        OMX_U32 nPortIndex;
        OMX_PARAM_PORTDEFINITIONTYPE sPortDefinition;

        oCallbacks.EventHandler    =  BufferTest_EventHandler;
        oCallbacks.EmptyBufferDone =  StubbedEmptyBufferDone;
        oCallbacks.FillBufferDone  =  StubbedFillBufferDone;

        pCtx = &ctx;
        pCtx->hStateChangeEvent = 0x0;
        pCtx->hPortDisableEvent = 0x0;
        pCtx->hPortEnableEvent = 0x0;
        pCtx->hPortErrorEvent = 0x0;
        pCtx->aPorts = 0x0;
        pCtx->bRestartAllPorts = OMX_FALSE;
        pCtx->bStopAllPorts = OMX_FALSE;

        /* initialize events to track callbacks */
        OMX_OSAL_EventCreate(&pCtx->hStateChangeEvent);
        OMX_OSAL_EventReset(pCtx->hStateChangeEvent);
        OMX_OSAL_EventCreate(&pCtx->hPortDisableEvent);
        OMX_OSAL_EventReset(pCtx->hPortDisableEvent);
        OMX_OSAL_EventCreate(&pCtx->hPortEnableEvent);
        OMX_OSAL_EventReset(pCtx->hPortEnableEvent);
        OMX_OSAL_EventCreate(&pCtx->hPortErrorEvent);
        OMX_OSAL_EventReset(pCtx->hPortErrorEvent);

        eError = OMX_CONF_CallbackTracerCreate(&oCallbacks, (OMX_PTR)pCtx, cComponentName,
                                               &pWrappedCallbacks, &pWrappedAppData);
        OMX_CONF_BAIL_ON_ERROR(eError);

        /* Initialize OpenMax */
        eError = OMX_Init();
        OMX_CONF_BAIL_ON_ERROR(eError);

        eError = OMX_GetHandle(&hComp, cComponentName, pWrappedAppData, pWrappedCallbacks);
        OMX_CONF_BAIL_ON_ERROR(eError);
        eError = OMX_CONF_ComponentTracerCreate(hComp, cComponentName, &hWrappedComp);
        OMX_CONF_BAIL_ON_ERROR(eError);

        pCtx->hWrappedComp = hWrappedComp;

        OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "detected all port on component %s\n", cComponentName);
        /* inspect component's ports */
        OMX_CONF_INIT_STRUCT(pCtx->sPortParam[0], OMX_PORT_PARAM_TYPE);
        eError = OMX_GetParameter(hWrappedComp, OMX_IndexParamAudioInit, (OMX_PTR) & pCtx->sPortParam[0]);
        if (OMX_ErrorUnsupportedIndex == eError)  eError = OMX_ErrorNone;
        OMX_CONF_BAIL_ON_ERROR(eError);
        OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "detected %i audio ports starting at %i \n",
                       pCtx->sPortParam[0].nPorts, pCtx->sPortParam[0].nStartPortNumber);

        /* detect all video ports on the component */
        OMX_CONF_INIT_STRUCT(pCtx->sPortParam[1], OMX_PORT_PARAM_TYPE);
        eError = OMX_GetParameter(hWrappedComp, OMX_IndexParamVideoInit, (OMX_PTR) & pCtx->sPortParam[1]);
        if (OMX_ErrorUnsupportedIndex == eError)  eError = OMX_ErrorNone;
        OMX_CONF_BAIL_ON_ERROR(eError);
        OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "detected %i video ports starting at %i \n",
                       pCtx->sPortParam[1].nPorts, pCtx->sPortParam[1].nStartPortNumber);

        /* detect all image ports on the component */
        OMX_CONF_INIT_STRUCT(pCtx->sPortParam[2], OMX_PORT_PARAM_TYPE);
        eError = OMX_GetParameter(hWrappedComp, OMX_IndexParamImageInit, (OMX_PTR) & pCtx->sPortParam[2]);
        if (OMX_ErrorUnsupportedIndex == eError)  eError = OMX_ErrorNone;
        OMX_CONF_BAIL_ON_ERROR(eError);
        OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "detected %i image ports starting at %i \n",
                       pCtx->sPortParam[2].nPorts, pCtx->sPortParam[2].nStartPortNumber);

        /* detect all other ports on the component */
        OMX_CONF_INIT_STRUCT(pCtx->sPortParam[3], OMX_PORT_PARAM_TYPE);
        eError = OMX_GetParameter(hWrappedComp, OMX_IndexParamOtherInit, (OMX_PTR) & pCtx->sPortParam[3]);
        if (OMX_ErrorUnsupportedIndex == eError)  eError = OMX_ErrorNone;
        OMX_CONF_BAIL_ON_ERROR(eError);
        OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "detected %i other ports starting at %i \n",
                       pCtx->sPortParam[3].nPorts, pCtx->sPortParam[3].nStartPortNumber);

        /* record total number of ports and allocate port structures */
        pCtx->nNumPorts = pCtx->sPortParam[0].nPorts +
                          pCtx->sPortParam[1].nPorts +
                          pCtx->sPortParam[2].nPorts +
                          pCtx->sPortParam[3].nPorts;

        if (0x0 == pCtx->nNumPorts)
        {
            OMX_CONF_SET_ERROR_BAIL(eError, OMX_ErrorUndefined, "Component has no ports\n");
        }

        /* allocate port structures */
        eError = BufferTest_AllocatePortStructures(pCtx);
        OMX_CONF_BAIL_ON_ERROR(eError);

        /* transition component to idle, verifying that the component does not
           go to IDLE within a certain timeout */
        OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Command component to OMX_StateIdle\n");
        OMX_OSAL_EventReset(pCtx->hStateChangeEvent);
        eError = OMX_SendCommand(hWrappedComp, OMX_CommandStateSet, OMX_StateIdle, 0x0);
        OMX_CONF_BAIL_ON_ERROR(eError);

        /* allocate some buffers on the ports, vertifying the component does
           not transition to idle */
        OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Allocate some buffers on all ports\n");
        eError = BufferTest_AllocateAllButOne(pCtx);
        OMX_CONF_BAIL_ON_ERROR(eError);

        OMX_OSAL_EventWait(pCtx->hStateChangeEvent, OMX_CONF_TIMEOUT_EXPECTING_FAILURE, &bTimeout);
        if (OMX_FALSE == bTimeout)
        {
            OMX_CONF_SET_ERROR_BAIL(eError, OMX_ErrorUndefined, "Unexpected state transition to OMX_StateIdle\n");
        }

        /* allocate all buffers on the ports, vertifying the component does
           transition to idle */
        OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Allocate remaining buffers on all ports\n");
        eError = BufferTest_AllocateAllPlusOne(pCtx);
        OMX_CONF_BAIL_ON_ERROR(eError);
        OMX_OSAL_EventWait(pCtx->hStateChangeEvent, OMX_CONF_TIMEOUT_EXPECTING_SUCCESS, &bTimeout);
        if (OMX_TRUE == bTimeout)
        {
            OMX_CONF_SET_ERROR_BAIL(eError, OMX_ErrorUndefined, "State transition to OMX_StateIdle never occured\n");
        }

        /* transition the component to from idle to loaded, verifying the component
           does not transition */
        OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Command component to OMX_StateLoaded\n");
        OMX_OSAL_EventReset(pCtx->hStateChangeEvent);
        eError = OMX_SendCommand(hWrappedComp, OMX_CommandStateSet, OMX_StateLoaded, 0x0);
        OMX_CONF_BAIL_ON_ERROR(eError);

        /* free some buffers */
        eError = BufferTest_FreeAllButOne(pCtx);
        OMX_CONF_BAIL_ON_ERROR(eError);
        OMX_OSAL_EventWait(pCtx->hStateChangeEvent, OMX_CONF_TIMEOUT_EXPECTING_FAILURE, &bTimeout);
        if (OMX_FALSE == bTimeout)
        {
            OMX_CONF_SET_ERROR_BAIL(eError, OMX_ErrorUndefined, "Unexpected state transition to OMX_StateLoaded\n");
        }

        /* free all buffers and confirm component transitions to loaded */
        OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Free buffers on all ports\n");
        eError = BufferTest_FreeAll(pCtx);
        OMX_CONF_BAIL_ON_ERROR(eError);
        OMX_OSAL_EventWait(pCtx->hStateChangeEvent, OMX_CONF_TIMEOUT_EXPECTING_SUCCESS, &bTimeout);
        if (OMX_TRUE == bTimeout)
        {
            OMX_CONF_SET_ERROR_BAIL(eError, OMX_ErrorUndefined, "Expected state transition to OMX_StateLoaded\n");
        }

        /* stop all ports */
        OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Command all ports to disabled\n");
        pCtx->bStopAllPorts = OMX_TRUE;
        pCtx->nNumPortsStopped = 0x0;
        OMX_OSAL_EventReset(pCtx->hPortDisableEvent);
        eError = OMX_SendCommand(hWrappedComp, OMX_CommandPortDisable, OMX_ALL, 0x0);
        OMX_CONF_BAIL_ON_ERROR(eError);
        OMX_OSAL_EventWait(pCtx->hPortDisableEvent, OMX_CONF_TIMEOUT_EXPECTING_SUCCESS, &bTimeout);
        if (OMX_TRUE == bTimeout)
        {
            OMX_CONF_SET_ERROR_BAIL(eError, OMX_ErrorUndefined, "All ports not disabled\n");
        }
        pCtx->bStopAllPorts = OMX_FALSE;

        /* set the component to idle */
        OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Command component to OMX_StateIdle\n");
        OMX_OSAL_EventReset(pCtx->hStateChangeEvent);
        eError = OMX_SendCommand(hWrappedComp, OMX_CommandStateSet, OMX_StateIdle, 0x0);
        OMX_CONF_BAIL_ON_ERROR(eError);
        OMX_OSAL_EventWait(pCtx->hStateChangeEvent, OMX_CONF_TIMEOUT_EXPECTING_SUCCESS, &bTimeout);
        if (OMX_TRUE == bTimeout)
        {
            OMX_CONF_SET_ERROR_BAIL(eError, OMX_ErrorUndefined, "Expected state transition to OMX_StateIdle\n");
        }

        pPort = pCtx->aPorts;

        for (i = 0; i < pCtx->nNumPorts; i++)
        {
            /* verify port enable and populated status */
            nPortIndex =  pPort->sPortDef.nPortIndex;
            OMX_CONF_INIT_STRUCT(sPortDefinition, OMX_PARAM_PORTDEFINITIONTYPE);
            sPortDefinition.nPortIndex = nPortIndex;
            eError = OMX_GetParameter(pCtx->hWrappedComp, OMX_IndexParamPortDefinition,
                                      (OMX_PTR) & sPortDefinition);
            OMX_CONF_BAIL_ON_ERROR(eError);

            OMX_CONF_ASSERT(eError, (OMX_FALSE == sPortDefinition.bEnabled),
                            "Incorrect value in PortDefinition bEnabled field\n");
            OMX_CONF_ASSERT(eError, (OMX_FALSE == sPortDefinition.bPopulated),
                            "Incorrect value in PortDefinition bPopulated field\n");

            /* enable port, and verify it does not restart */
            OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Command port %i to enabled\n", nPortIndex);
            OMX_OSAL_EventReset(pCtx->hPortEnableEvent);
            pCtx->nRestartPort = nPortIndex;
            eError = OMX_SendCommand(hWrappedComp, OMX_CommandPortEnable, nPortIndex, 0x0);
            OMX_CONF_BAIL_ON_ERROR(eError);
            OMX_OSAL_EventWait(pCtx->hPortEnableEvent, OMX_CONF_TIMEOUT_EXPECTING_FAILURE, &bTimeout);
            if (OMX_FALSE == bTimeout)
            {
                OMX_CONF_SET_ERROR_BAIL(eError, OMX_ErrorUndefined, "Port enabled unexpectedly\n");
            }

            /* verify port enabled, but not populated */
            OMX_CONF_INIT_STRUCT(sPortDefinition, OMX_PARAM_PORTDEFINITIONTYPE);
            sPortDefinition.nPortIndex = nPortIndex;
            eError = OMX_GetParameter(pCtx->hWrappedComp, OMX_IndexParamPortDefinition,
                                      (OMX_PTR) & sPortDefinition);
            OMX_CONF_BAIL_ON_ERROR(eError);

            OMX_CONF_ASSERT(eError, (OMX_TRUE == sPortDefinition.bEnabled),
                            "Incorrect value in PortDefinition bEnabled field\n");
            OMX_CONF_ASSERT(eError, (OMX_FALSE == sPortDefinition.bPopulated),
                            "Incorrect value in PortDefinition bPopulated field\n");

            /* allocate buffers on the port, and verify it restarts */
            OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Allocate buffers on port %i\n", nPortIndex);
            eError = BufferTest_PortAllocateNumBuffers(pCtx, pPort, (pPort->sPortDef.nBufferCountActual));
            OMX_CONF_BAIL_ON_ERROR(eError);
            OMX_OSAL_EventWait(pCtx->hPortEnableEvent, OMX_CONF_TIMEOUT_EXPECTING_SUCCESS, &bTimeout);
            if (OMX_TRUE == bTimeout)
            {
                OMX_CONF_SET_ERROR_BAIL(eError, OMX_ErrorUndefined, "Port never enabled\n");
            }

            /* verify port enabled and populated */
            OMX_CONF_INIT_STRUCT(sPortDefinition, OMX_PARAM_PORTDEFINITIONTYPE);
            sPortDefinition.nPortIndex = nPortIndex;
            eError = OMX_GetParameter(pCtx->hWrappedComp, OMX_IndexParamPortDefinition,
                                      (OMX_PTR) & sPortDefinition);
            OMX_CONF_BAIL_ON_ERROR(eError);

            OMX_CONF_ASSERT(eError, (OMX_TRUE == sPortDefinition.bEnabled),
                            "Incorrect value in PortDefinition bEnabled field\n");
            OMX_CONF_ASSERT(eError, (OMX_TRUE == sPortDefinition.bPopulated),
                            "Incorrect value in PortDefinition bPopulated field\n");

            /* stop port, verifying it does not stop */
            OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Command port %i to disabled\n", nPortIndex);
            OMX_OSAL_EventReset(pCtx->hPortDisableEvent);
            pCtx->nStopPort = nPortIndex;
            eError = OMX_SendCommand(hWrappedComp, OMX_CommandPortDisable, nPortIndex, 0x0);
            OMX_CONF_BAIL_ON_ERROR(eError);
            OMX_OSAL_EventWait(pCtx->hPortDisableEvent, OMX_CONF_TIMEOUT_EXPECTING_FAILURE, &bTimeout);
            if (OMX_FALSE == bTimeout)
            {
                OMX_CONF_SET_ERROR_BAIL(eError, OMX_ErrorUndefined, "Port disabled unexpectedly\n");
            }

            /* free buffers on the port, verifying it stops */
            OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Free buffers on port %i\n", nPortIndex);
            eError = BufferTest_PortFreeNumBuffers(pCtx, pPort, LIFO_INQUEUE(pPort->pLifo));
            OMX_CONF_BAIL_ON_ERROR(eError);
            OMX_OSAL_EventWait(pCtx->hPortDisableEvent, OMX_CONF_TIMEOUT_EXPECTING_SUCCESS, &bTimeout);
            if (OMX_TRUE == bTimeout)
            {
                OMX_CONF_SET_ERROR_BAIL(eError, OMX_ErrorUndefined, "Port never disabled\n");
            }

            /* verify port not enabled, not populated */
            OMX_CONF_INIT_STRUCT(sPortDefinition, OMX_PARAM_PORTDEFINITIONTYPE);
            sPortDefinition.nPortIndex = nPortIndex;
            eError = OMX_GetParameter(pCtx->hWrappedComp, OMX_IndexParamPortDefinition,
                                      (OMX_PTR) & sPortDefinition);
            OMX_CONF_BAIL_ON_ERROR(eError);

            OMX_CONF_ASSERT(eError, (OMX_FALSE == sPortDefinition.bEnabled),
                            "Incorrect value in PortDefinition bEnabled field\n");
            OMX_CONF_ASSERT(eError, (OMX_FALSE == sPortDefinition.bPopulated),
                            "Incorrect value in PortDefinition bPopulated field\n");

            /* enable the port and allocate buffers */
            OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Command port %i to enabled\n", nPortIndex);
            OMX_OSAL_EventReset(pCtx->hPortEnableEvent);
            eError = OMX_SendCommand(hWrappedComp, OMX_CommandPortEnable, nPortIndex, 0x0);
            OMX_CONF_BAIL_ON_ERROR(eError);
            OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Allocate buffers on port %i\n", nPortIndex);
            eError = BufferTest_PortAllocateNumBuffers(pCtx, pPort, (pPort->sPortDef.nBufferCountActual));
            OMX_CONF_BAIL_ON_ERROR(eError);
            OMX_OSAL_EventWait(pCtx->hPortEnableEvent, OMX_CONF_TIMEOUT_EXPECTING_SUCCESS, &bTimeout);
            if (OMX_TRUE == bTimeout)
            {
                OMX_CONF_SET_ERROR_BAIL(eError, OMX_ErrorUndefined, "Port never enabled\n");
            }

            /* test the port errors when buffers are freed */
            OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Free buffers on port %i\n", nPortIndex);
            OMX_OSAL_EventReset(pCtx->hPortErrorEvent);
            eError = BufferTest_PortFreeNumBuffers(pCtx, pPort, LIFO_INQUEUE(pPort->pLifo));
            OMX_CONF_BAIL_ON_ERROR(eError);

            /* waiting for component to report error due to lost buffers */
            OMX_OSAL_EventWait(pCtx->hPortErrorEvent, OMX_CONF_TIMEOUT_EXPECTING_SUCCESS, &bTimeout);
            if (OMX_TRUE == bTimeout)
            {
                OMX_CONF_SET_ERROR_BAIL(eError, OMX_ErrorUndefined,
                                        "Component did not report OMX_ErrorPortUnpopulated\n");
            }

            /* verify port enabled, but not populated */
            OMX_CONF_INIT_STRUCT(sPortDefinition, OMX_PARAM_PORTDEFINITIONTYPE);
            sPortDefinition.nPortIndex = nPortIndex;
            eError = OMX_GetParameter(pCtx->hWrappedComp, OMX_IndexParamPortDefinition,
                                      (OMX_PTR) & sPortDefinition);
            OMX_CONF_BAIL_ON_ERROR(eError);

            OMX_CONF_ASSERT(eError, (OMX_TRUE == sPortDefinition.bEnabled),
                            "Incorrect value in PortDefinition bEnabled field\n");
            OMX_CONF_ASSERT(eError, (OMX_FALSE == sPortDefinition.bPopulated),
                            "Incorrect value in PortDefinition bPopulated field\n");

            /* stop the port */
            OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Command port %i to disabled\n", nPortIndex);
            OMX_OSAL_EventReset(pCtx->hPortDisableEvent);
            pCtx->nStopPort = nPortIndex;
            eError = OMX_SendCommand(hWrappedComp, OMX_CommandPortDisable, nPortIndex, 0x0);
            OMX_OSAL_EventWait(pCtx->hPortDisableEvent, OMX_CONF_TIMEOUT_EXPECTING_SUCCESS, &bTimeout);
            if (OMX_TRUE == bTimeout)
            {
                OMX_CONF_SET_ERROR_BAIL(eError, OMX_ErrorUndefined, "Port never disabled\n");
            }

            /* verify port not enabled, but not populated */
            OMX_CONF_INIT_STRUCT(sPortDefinition, OMX_PARAM_PORTDEFINITIONTYPE);
            sPortDefinition.nPortIndex = nPortIndex;
            eError = OMX_GetParameter(pCtx->hWrappedComp, OMX_IndexParamPortDefinition,
                                      (OMX_PTR) & sPortDefinition);
            OMX_CONF_BAIL_ON_ERROR(eError);

            OMX_CONF_ASSERT(eError, (OMX_FALSE == sPortDefinition.bEnabled),
                            "Incorrect value in PortDefinition bEnabled field\n");
            OMX_CONF_ASSERT(eError, (OMX_FALSE == sPortDefinition.bPopulated),
                            "Incorrect value in PortDefinition bPopulated field\n");

            pPort++;
        }

        /* transition component from idle to loaded */
        OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Command component to OMX_StateLoaded\n");
        OMX_OSAL_EventReset(pCtx->hStateChangeEvent);
        eError = OMX_SendCommand(hWrappedComp, OMX_CommandStateSet, OMX_StateLoaded, 0x0);
        OMX_CONF_BAIL_ON_ERROR(eError);
        OMX_OSAL_EventWait(pCtx->hStateChangeEvent, OMX_CONF_TIMEOUT_EXPECTING_SUCCESS, &bTimeout);
        if (OMX_TRUE == bTimeout)
        {
            OMX_CONF_SET_ERROR_BAIL(eError, OMX_ErrorUndefined, "Expected state transition to OMX_StateLoaded\n");
        }

        /* restart all ports */
        OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "Command all ports to enable\n");
        pCtx->bRestartAllPorts = OMX_TRUE;
        pCtx->nNumPortsRestarted = 0x0;
        OMX_OSAL_EventReset(pCtx->hPortEnableEvent);
        eError = OMX_SendCommand(hWrappedComp, OMX_CommandPortEnable, OMX_ALL, 0x0);
        OMX_CONF_BAIL_ON_ERROR(eError);
        OMX_OSAL_EventWait(pCtx->hPortEnableEvent, OMX_CONF_TIMEOUT_EXPECTING_SUCCESS, &bTimeout);
        if (OMX_TRUE == bTimeout)
        {
            OMX_CONF_SET_ERROR_BAIL(eError, OMX_ErrorUndefined, "All ports not enabled\n");
        }
        pCtx->bRestartAllPorts = OMX_FALSE;


OMX_CONF_TEST_BAIL:

        eCleanupError = BufferTest_FreePortStructures(pCtx);

        if (hWrappedComp)
        {
            OMX_CONF_ComponentTracerDestroy(hWrappedComp);
        }

        if (hComp)
        {
            if (OMX_ErrorNone == eCleanupError)
            {
                eCleanupError = OMX_FreeHandle(hComp);

            }
            else
            {
                OMX_FreeHandle(hComp);
            }
        }

        if (OMX_ErrorNone != eCleanupError)
        {
            OMX_Deinit();

        }
        else
        {
            eCleanupError = OMX_Deinit();
        }

        OMX_OSAL_EventDestroy(pCtx->hStateChangeEvent);
        OMX_OSAL_EventDestroy(pCtx->hPortDisableEvent);
        OMX_OSAL_EventDestroy(pCtx->hPortEnableEvent);
        OMX_OSAL_EventDestroy(pCtx->hPortErrorEvent);

        if (OMX_ErrorNone == eError)
        {
            /* if there were no failures during the test, report any errors found
               during cleanup */
            eError = eCleanupError;
        }

        return(eError);
    }
Пример #24
0
int main(int argc, char **argv)
{
    int bufCnt=0;
    OMX_ERRORTYPE result;
    struct sigaction sa;


    struct wav_header hdr;
    int bytes_writen = 0;

    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = &signal_handler;
    sigaction(SIGABRT, &sa, NULL);
    sigaction(SIGUSR1, &sa, NULL);
    sigaction(SIGUSR2, &sa, NULL);

    pthread_cond_init(&cond, 0);
    pthread_mutex_init(&lock, 0);


    if (argc >= 8) {
      in_filename = argv[1];
      samplerate = atoi(argv[2]);
      channels = atoi(argv[3]);
      pcmplayback = atoi(argv[4]);
      tunnel  = atoi(argv[5]);
        filewrite = atoi(argv[6]);
      sbr_ps_enabled = atoi(argv[7]);
      if (tunnel == 1) {
           pcmplayback = 0; /* This feature holds good only for non tunnel mode*/
            filewrite = 0;  /* File write not supported in tunnel mode */
      }
    } else {

        DEBUG_PRINT(" invalid format: \n");
        DEBUG_PRINT("ex: ./mm-adec-omxaac AACINPUTFILE SAMPFREQ CHANNEL PCMPLAYBACK TUNNEL FILEWRITE\n");
        DEBUG_PRINT( "PCMPLAYBACK = 1 (ENABLES PCM PLAYBACK IN NON TUNNEL MODE) \n");
        DEBUG_PRINT( "PCMPLAYBACK = 0 (DISABLES PCM PLAYBACK IN NON TUNNEL MODE) \n");
        DEBUG_PRINT( "TUNNEL = 1 (DECODED AAC SAMPLES IS PLAYED BACK)\n");
        DEBUG_PRINT( "TUNNEL = 0 (DECODED AAC SAMPLES IS LOOPED BACK TO THE USER APP)\n");
        DEBUG_PRINT( "FILEWRITE = 1 (ENABLES PCM FILEWRITE IN NON TUNNEL MODE) \n");
        DEBUG_PRINT( "FILEWRITE = 0 (DISABLES PCM FILEWRITE IN NON TUNNEL MODE) \n");
        DEBUG_PRINT( "SBR_PS_ENABLED = 0 (SBR AND PS DISABLED) \n");
        DEBUG_PRINT( "SBR_PS_ENABLED = 1 (SBR IS ENABLED) \n");
        DEBUG_PRINT( "SBR_PS_ENABLED = 2 (SBR AND PS ENABLED) \n");
        return 0;
    }

    if(tunnel == 0)
        aud_comp = "OMX.qcom.audio.decoder.aac";
    else
        aud_comp = "OMX.qcom.audio.decoder.tunneled.aac";

    printf("Init_Decoder()\n");
    if(Init_Decoder(aud_comp)!= 0x00)
    {
        DEBUG_PRINT("Decoder Init failed\n");
        return -1;
    }

    printf("Play_Decoder()\n");
    if(Play_Decoder() != 0x00)
    {
        DEBUG_PRINT("Play_Decoder failed\n");
        return -1;
    }
     printf("Play_Decoder() done\n");

    // Wait till EOS is reached...

   printf("************* before wait_for_event\n");
    wait_for_event();
   printf(" after wait_for_event bOutputEosReached %d tunnel %d bInputEosReached %d \n",bOutputEosReached,tunnel,bInputEosReached);
   if(bOutputEosReached || (tunnel && bInputEosReached)) {

        DEBUG_PRINT(" going to sleep \n");
       // sleep(15);
        DEBUG_PRINT(" wake up \n");
        /******************************************************************/
        #ifdef PCM_PLAYBACK
        if(pcmplayback == 1)
        {
            ioctl(m_pcmdrv_fd, AUDIO_STOP, 0);

            if(m_pcmdrv_fd >= 0) {
                close(m_pcmdrv_fd);
                m_pcmdrv_fd = -1;
                DEBUG_PRINT(" PCM device closed succesfully \n");
            }
            else
            {
                DEBUG_PRINT(" PCM device close failure \n");
            }
        }
        #endif // PCM_PLAYBACK

        if((tunnel == 0)&& (filewrite == 1))
        {
            hdr.riff_id = ID_RIFF;
            hdr.riff_sz = 0;
            hdr.riff_fmt = ID_WAVE;
            hdr.fmt_id = ID_FMT;
            hdr.fmt_sz = 16;
            hdr.audio_format = FORMAT_PCM;
            hdr.num_channels = channels;//2;
            hdr.sample_rate = samplerate; //SAMPLE_RATE;  //44100;
            hdr.byte_rate = hdr.sample_rate * hdr.num_channels * 2;
            hdr.block_align = hdr.num_channels * 2;
            hdr.bits_per_sample = 16;
            hdr.data_id = ID_DATA;
            hdr.data_sz = 0;

            DEBUG_PRINT("output file closed and EOS reached total decoded data length %d\n",totaldatalen);
            hdr.data_sz = totaldatalen;
            hdr.riff_sz = totaldatalen + 8 + 16 + 8;
            fseek(outputBufferFile, 0L , SEEK_SET);
            bytes_writen = fwrite(&hdr,1,sizeof(hdr),outputBufferFile);
            if (bytes_writen <= 0) {
                DEBUG_PRINT("Invalid Wav header write failed\n");
            }
            bFileclose = 1;
            fclose(outputBufferFile);
        }
        /************************************************************************************/
        DEBUG_PRINT("\nMoving the decoder to idle state \n");
        OMX_SendCommand(aac_dec_handle, OMX_CommandStateSet, OMX_StateIdle,0);
        wait_for_event();

        DEBUG_PRINT("\nMoving the decoder to loaded state \n");
        OMX_SendCommand(aac_dec_handle, OMX_CommandStateSet, OMX_StateLoaded,0);

        DEBUG_PRINT("\nFillBufferDone: Deallocating i/p buffers \n");
        for(bufCnt=0; bufCnt < input_buf_cnt; ++bufCnt) {
            OMX_FreeBuffer(aac_dec_handle, 0, pInputBufHdrs[bufCnt]);
        }

        if(tunnel == 0)
        {
            DEBUG_PRINT("\nFillBufferDone: Deallocating o/p buffers \n");
            for(bufCnt=0; bufCnt < output_buf_cnt; ++bufCnt) {
            OMX_FreeBuffer(aac_dec_handle, 1, pOutputBufHdrs[bufCnt]);
            }
        }


        ebd_cnt=0;
        bInputEosReached = false;
            wait_for_event();
            ebd_cnt=0;
        bOutputEosReached = false;
        result = OMX_FreeHandle(aac_dec_handle);
        if (result != OMX_ErrorNone) {
            DEBUG_PRINT ("\nOMX_FreeHandle error. Error code: %d\n", result);
        }
           aac_dec_handle = NULL;

        /* Deinit OpenMAX */

        OMX_Deinit();

        pthread_cond_destroy(&cond);
        pthread_mutex_destroy(&lock);
        DEBUG_PRINT("*****************************************\n");
        DEBUG_PRINT("******...TEST COMPLETED...***************\n");
        DEBUG_PRINT("*****************************************\n");
    }
    return 0;
}
OMX_ERRORTYPE unload_component(HTEST *hTest)
{
    OMX_FreeHandle(hTest->hComponent);
    fsl_osal_thread_destroy(hTest->pThreadId);
    return OMX_ErrorNone;
}
Пример #26
0
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;
}
Пример #27
0
int jpege_main(void *Param) {
    OMX_PARAM_PORTDEFINITIONTYPE asPortDefinition[2];
    OMX_PORT_PARAM_TYPE sImageInit;
    OMX_IMAGE_PARAM_PORTFORMATTYPE sImageParamPortformatType;
    OMX_CALLBACKTYPE sCallbacks;
    OMX_IMAGE_PARAM_QFACTORTYPE sImageParamQFacttype;
    int i = 0, j = 0;
    OMX_ERRORTYPE err = OMX_ErrorNone;
    OMX_STATETYPE state = OMX_StateMax;
    OMX_U32 nQFactor = 0;
    OMX_S8 **cName;
    OMX_U32 numComp;
    char ConfigFileName[256];
    OMX_S8 componentName[256];
    OMX_VERSIONTYPE componentVer;
    OMX_VERSIONTYPE specVer;
    OMX_UUIDTYPE componentUUID;
    void *InputPortRet, *OutputPortRet, *OutputDataRet;

    memset(asPortDefinition, 0, sizeof(asPortDefinition));
    memset(&sImageInit, 0, sizeof(sImageInit));
    memset(&sImageParamPortformatType, 0, sizeof(sImageParamPortformatType));
    memset(&sCallbacks, 0, sizeof(sCallbacks));

    output_mode = ((VIDEODECFUNCPARAMTYPE *) Param)->Mode;
    nFrameWidth = ((VIDEODECFUNCPARAMTYPE *) Param)->nFrameWidth;
    nFrameHeight = ((VIDEODECFUNCPARAMTYPE *) Param)->nFrameHeight;
    eColorFormat = ((VIDEODECFUNCPARAMTYPE *) Param)->eColorFormat;
    nQFactor = ((VIDEODECFUNCPARAMTYPE *) Param)->nQFactor;
    int ret = 0, hasHandle = 0, commandValue = 0, hasNoWait = 1; /* */

    ef = ff = 0;

    if ((frameSize = yuv_framesize(nFrameWidth, nFrameHeight, eColorFormat)) <= 0) {
        FILE_DBG1("[emxx_jpeglib][%d] yuv_init\n", __LINE__);
        return -1;
    }

    strcpy(ConfigFileName, AV_CODEC_CONFIG_FILE_NAME);

    err = OMF_SetLogMode(0x00000001);
    if (err != OMX_ErrorNone)
    {
        FILE_DBG1("[emxx_jpeglib] Can't set log mode! error code = 0x%08x\n", err);
        goto jpege_end;
    }

    err = OMF_SetConfiguration(ConfigFileName);
    if (err != OMX_ErrorNone)
    {
        FILE_DBG1("[emxx_jpeglib] Can't set configuration file! error code = 0x%08x\n", err);
        goto jpege_end;
    }

    err = OMX_Init();

    if (err != OMX_ErrorNone) {
        FILE_DBG("can't initialize OMX LIb, exit\n");
        goto jpege_end;
    }

    /* Get MC Name */
    cName = (OMX_U8 **) malloc(sizeof(OMX_U8 *));
    cName[0] = (OMX_U8 *) malloc(128 * sizeof(OMX_U8));
    numComp = 1;
    err = OMX_GetComponentsOfRole(JPEGE_ROLE, &numComp, cName);
    if (err != OMX_ErrorNone) {
        FILE_DBG1("[emxx_jpeglib] Can't get component name! error code = 0x%8x\n", err);
    } else {
        FILE_DBG1("OMF Name = %s\n", cName[0]);
    }

    /* Get Media Component handle. */
    sCallbacks.EventHandler = event_handler;
    sCallbacks.EmptyBufferDone = empty_buffer_done;
    sCallbacks.FillBufferDone = fill_buffer_done;
    err = OMX_GetHandle(&Video_hComponent, cName[0], NULL, &sCallbacks);
    if (err != OMX_ErrorNone) {
        FILE_DBG2("[emxx_jpeglib][%d] Can't get handle! erro code = 0x%08x\n", __LINE__,
                err);
        free(cName[0]);
        free(cName);
        ret = -1;
        goto jpege_end;
    }
    hasHandle = 1;
    free(cName[0]);
    free(cName);

    /* GetComponentVersion */
    err = OMX_GetComponentVersion(Video_hComponent, componentName,
            &componentVer, &specVer, &componentUUID);
    if (err != OMX_ErrorNone) {
        FILE_DBG2(
                "[emxx_jpeglib][%d] Can't get component version! error code = 0x%08x\n",
                __LINE__, err);
        return -1;
    } else {
        printf("Component Version = 0x%08x\n", componentVer);
        printf("Spec      Version = 0x%08x\n", specVer);
    }

    /* Get OMX_IndexParamImageInit. */
    sImageInit.nSize = sizeof(OMX_PORT_PARAM_TYPE);
    err = OMX_GetParameter(Video_hComponent, OMX_IndexParamImageInit,
            &sImageInit);
    if (err != OMX_ErrorNone) {
        FILE_DBG2("[emxx_jpeglib][%d] Can't get parameter! erro code = 0x%08x\n",
                __LINE__, err);
        ret = -1;
        goto jpege_end;
    }

    /* Get & Set OMX_IndexParamPortDefinition. */
    for (i = 0; i < sImageInit.nPorts; i++) {
        asPortDefinition[i].nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE);
        asPortDefinition[i].nPortIndex = sImageInit.nStartPortNumber + i;
        err = OMX_GetParameter(Video_hComponent, OMX_IndexParamPortDefinition,
                &asPortDefinition[i]);
        if (err != OMX_ErrorNone) {
            FILE_DBG2("[emxx_jpeglib][%d] Can't get parameter! erro code = 0x%08x\n",
                    __LINE__, err);
            ret = -1;
            goto jpege_end;
        }

        if (i == PORT_OFFSET_INPUT) /* VPB+0 */
        {
            asPortDefinition[PORT_OFFSET_INPUT].format.image.nFrameWidth
                    = nFrameWidth;
            asPortDefinition[PORT_OFFSET_INPUT].format.image.nFrameHeight
                    = nFrameHeight;
            asPortDefinition[PORT_OFFSET_INPUT].format.image.eColorFormat
                    = eColorFormat;
            err = OMX_SetParameter(Video_hComponent,
                    OMX_IndexParamPortDefinition,
                    &asPortDefinition[PORT_OFFSET_INPUT]);
            if (err != OMX_ErrorNone) {
                extern int end_flag;
                printf(
                        "[emxx_jpeglib][%d] Can't set parameter! erro code = 0x%08x\n",
                        __LINE__, err);
                ret = -1;
                goto jpege_end;
            }
        }
    }

    nVideoPortIndex[PORT_OFFSET_INPUT]
            = asPortDefinition[PORT_OFFSET_INPUT].nPortIndex;
    nVideoPortIndex[PORT_OFFSET_OUTPUT]
            = asPortDefinition[PORT_OFFSET_OUTPUT].nPortIndex;

    VideoInputBuffNum = asPortDefinition[PORT_OFFSET_INPUT].nBufferCountActual;
    VideoOutputBuffNum
            = asPortDefinition[PORT_OFFSET_OUTPUT].nBufferCountActual;

    printf("VideoInputBuffNum, %d    VideoOutputBuffNum, %d\n", VideoInputBuffNum, VideoOutputBuffNum);
    /* Get & Set OMX_IndexParamImagePortFormat. */
    sImageParamPortformatType.nSize = sizeof(OMX_IMAGE_PARAM_PORTFORMATTYPE);
    sImageParamPortformatType.nPortIndex = PORT_OFFSET_INPUT;
    sImageParamPortformatType.nIndex = nVideoPortIndex[PORT_OFFSET_INPUT];
    err = OMX_GetParameter(Video_hComponent, OMX_IndexParamImagePortFormat,
            &sImageParamPortformatType);
    if (err != OMX_ErrorNone) {
        FILE_DBG2("[emxx_jpeglib][%d] Can't get parameter! erro code = 0x%08x\n",
                __LINE__, err);
        ret = -1;
        goto jpege_end;
    }

    sImageParamPortformatType.nSize = sizeof(OMX_IMAGE_PARAM_PORTFORMATTYPE);
    sImageParamPortformatType.eColorFormat = eColorFormat;
    err = OMX_SetParameter(Video_hComponent, OMX_IndexParamImagePortFormat,
            &sImageParamPortformatType);
    if (err != OMX_ErrorNone) {
        FILE_DBG2("[emxx_jpeglib][%d] Can't get parameter! erro code = 0x%08x\n",
                __LINE__, err);
        ret = -1;
        goto jpege_end;
    }
    /* Change state to OMX_StateIdle from OMX_StateLoaded. */
    pthread_mutex_lock(&VideoMutex);
    err = OMX_SendCommand(Video_hComponent, OMX_CommandStateSet, OMX_StateIdle,
            NULL);
    if (err != OMX_ErrorNone) {
        FILE_DBG2("[emxx_jpeglib][%d] Can't send command! erro code = 0x%08x\n",
                __LINE__, err);
        ret = -1;
        goto jpege_end;
    }

    /* Allocate stream buffer. */
    for (i = 0; i < sImageInit.nPorts; i++) {
        for (j = 0; j < asPortDefinition[i].nBufferCountActual; j++) {
            err = OMX_AllocateBuffer(Video_hComponent, &apsVideoBuffer[i][j],
                    asPortDefinition[i].nPortIndex, NULL,
                    asPortDefinition[i].nBufferSize);
            if (err != OMX_ErrorNone) {
                FILE_DBG2(
                        "[emxx_jpeglib][%d] Can't allocate buffer! erro code = 0x%08x\n",
                        __LINE__, err);
                ret = -1;
                goto jpege_end;
            }

            FILE_DBG2("[%d][%d] allocated\n", i, j);
        }
    }

    /* Complete state transition. */
    pthread_cond_wait(&VideoCond, &VideoMutex);
    pthread_mutex_unlock(&VideoMutex);

    semaphore_init(CODEC_VIDEO, output_mode);
#if 1 
    /* Create data input thread. */
    if (pthread_create(&VideoInputThreadId, NULL,
            (void*) jpeg_input_port_thread, NULL) != 0) {
        FILE_DBG1("[emxx_jpeglib][%d] failed pthread_create input_port_thread\n",
                __LINE__);
        ret = -1;
        goto jpege_end;
    }

    /* Create data output thread. */
    if (pthread_create(&VideoOutputThreadId, NULL,
            (void*) jpeg_output_port_thread, NULL) != 0) {
        FILE_DBG1("[emxx_jpeglib][%d] failed output_port_thread\n", __LINE__);
        ret = -1;
        goto jpege_end;
    }

    /* Create data output thread */
    if (pthread_create(&VideoOutputDataThreadId, NULL,
            (void*) jpeg_output_data_thread, NULL) != 0) {
        FILE_DBG1("[emxx_jpeglib][%d] pthread_create output_data_thread\n", __LINE__);
        ret = -1;
        goto jpege_end;
    }
#endif
    /* Change state to OMX_StateExecuting form OMX_StateIdle. */
    pthread_mutex_lock(&VideoMutex);
    err = OMX_SendCommand(Video_hComponent, OMX_CommandStateSet,
            OMX_StateExecuting, NULL);
    if (err != OMX_ErrorNone) {
        FILE_DBG2("[emxx_jpeglib][%d] Can't send command! erro code = 0x%08x\n",
                __LINE__, err);
        ret = -1;
        goto jpege_end;
    }

    /* Complete state transition. */
    pthread_cond_wait(&VideoCond, &VideoMutex);
    pthread_mutex_unlock(&VideoMutex);

    FILE_DBG("state has been changed to executing\n");
    VideoOutputPortThreadLoopFlag = 1;

    while (!ef || !ff)
    {
        printf(".");
    }

    FILE_DBG("start close OMX\n");
    hasNoWait = 0;

    VideoOutputPortThreadLoopFlag = 0;

    pthread_mutex_lock(&VideoMutex);
    err = OMX_SendCommand(Video_hComponent, OMX_CommandStateSet, OMX_StateIdle, NULL);
    if (err != OMX_ErrorNone) {
        FILE_DBG("can't send command\n");
        ret = -1;
        goto jpege_end;
    }

    pthread_cond_wait(&VideoCond, &VideoMutex);
    pthread_mutex_unlock(&VideoMutex);

    /* Change state to OMX_StateLoaded from OMX_StateIdle. */
    pthread_mutex_lock(&VideoMutex);
    err = OMX_SendCommand(Video_hComponent, OMX_CommandStateSet,OMX_StateLoaded, NULL);
    if (err != OMX_ErrorNone) {
        FILE_DBG2("[emxx_jpeglib][%d] Can't send command! erro code = 0x%08x\n",
                __LINE__, err);
        ret = -1;
        goto jpege_end;
    }

    FILE_DBG("changed to loaded state\n");

    /* Free buffer. */
    for (i = 0; i < sImageInit.nPorts; i++) {
        for (j = 0; j < asPortDefinition[i].nBufferCountActual; j++) {
            err = OMX_FreeBuffer(Video_hComponent,
                    asPortDefinition[i].nPortIndex, apsVideoBuffer[i][j]);
            if (err != OMX_ErrorNone) {
                FILE_DBG2("[emxx_jpeglib][%d] Can't free buffer! erro code = 0x%08x\n",
                        __LINE__, err);
                ret = -1;
                goto jpege_end;
            }
        }
    }

    /* Complete state transition. */
    pthread_cond_wait(&VideoCond, &VideoMutex);
    pthread_mutex_unlock(&VideoMutex);

    jpege_end:
    FILE_DBG("free buffer\n");
    /* Free JPEG Media Component handle. */
    if (hasHandle) {
        err = OMX_FreeHandle(Video_hComponent);
        if (err != OMX_ErrorNone) {
            FILE_DBG2("[emxx_jpeglib][%d] Can't free handle! erro code = 0x%08x\n",
                    __LINE__, err);
            ret = -1;
        }
    }

    semaphore_deinit(CODEC_VIDEO, output_mode);
    FILE_DBG("close debug file");
    FILE_DBG_CLOSE();
    return 0;
}
void BaseEngine::close()
{
	ofLogVerbose(__func__) << "START";
	if(omxCameraSettings.doRecording)
	{
		//encoderOutputBuffer->nFlags = OMX_BUFFERFLAG_EOS;
		//OMX_FillThisBuffer(encoder, encoderOutputBuffer);
	}else 
	{
		//may have to revisit this if creating new instances of the videograbber
		//otherwise OMX components seem smart enough to clean up themselves on destruction
		ofLogVerbose(__func__) << "END - just exiting";
		isOpen = false;
		return;
	}
	
	
	if(omxCameraSettings.doRecording && !didWriteFile)
	{
		writeFile();
		
	}
	isOpen = false;
	return;
	ofLogVerbose(__func__) << "OMX BREAKDOWN START";
	
	OMX_SendCommand(camera, OMX_CommandFlush, CAMERA_OUTPUT_PORT, NULL);
	if(omxCameraSettings.doRecording)
	{
		OMX_SendCommand(encoder, OMX_CommandFlush, VIDEO_ENCODE_INPUT_PORT, NULL);
		OMX_SendCommand(encoder, OMX_CommandFlush, VIDEO_ENCODE_OUTPUT_PORT, NULL);
	}
	
	if(omxCameraSettings.doRecording)
	{
		OMXCameraUtils::disableAllPortsForComponent(&encoder);
	}
	OMXCameraUtils::disableAllPortsForComponent(&camera);
	
	if(omxCameraSettings.doRecording)
	{
		OMX_FreeBuffer(encoder, VIDEO_ENCODE_OUTPUT_PORT, encoderOutputBuffer);
	}
	
	OMX_SendCommand(camera, OMX_CommandStateSet, OMX_StateIdle, NULL);
	
	if(omxCameraSettings.doRecording)
	{
		OMX_SendCommand(encoder, OMX_CommandStateSet, OMX_StateIdle, NULL);
	}
	
	OMX_SendCommand(camera, OMX_CommandStateSet, OMX_StateLoaded, NULL);
	
	if(omxCameraSettings.doRecording)
	{
		OMX_SendCommand(encoder, OMX_CommandStateSet, OMX_StateLoaded, NULL);
	}
	
	OMX_FreeHandle(camera);
	if(omxCameraSettings.doRecording)
	{
		OMX_FreeHandle(encoder);
	}
	
	ofLogVerbose(__func__) << "OMX BREAKDOWN END";
	ofLogVerbose(__func__) << " END";
	isOpen = false;
}
    OMX_ERRORTYPE OMX_CONF_ComponentNameTest(OMX_IN OMX_STRING cComponentName)
    {
        OMX_ERRORTYPE  eError = OMX_ErrorNone;
        OMX_HANDLETYPE hComp  = 0;
        OMX_U32 i = 0;
        OMX_BOOL bNameValid = OMX_FALSE;
        OMX_BOOL bFound = OMX_FALSE;
        OMX_S8 cCompEnumName[TEST_COMPONENT_NAME_SIZE];
        OMX_CALLBACKTYPE sCallbacks;

        sCallbacks.EventHandler    = ComponentNameTest_EventHandler;
        sCallbacks.EmptyBufferDone = ComponentNameTest_EmptyBufferDone;
        sCallbacks.FillBufferDone  = ComponentNameTest_FillBufferDone;

        /* Initialize OpenMax */
        eError = OMX_Init();
        if (eError != OMX_ErrorNone)
        {
            goto OMX_CONF_TEST_BAIL;
        }

        while (OMX_ErrorNone == eError)
        {
            /* loop through all enumerated components to determine if the component name
               specificed for the test is enumerated by the OMX core */
            eError = OMX_ComponentNameEnum((OMX_STRING) cCompEnumName, TEST_COMPONENT_NAME_SIZE, i);
            if (OMX_ErrorNone == eError)
            {
                OMX_OSAL_Trace(OMX_OSAL_TRACE_INFO, "OMX_ComponenNameEnum enumerated %s at index %i\n",
                               cCompEnumName, i);

                if (!strcmp((OMX_STRING) cCompEnumName, cComponentName))
                {
                    /* component name enumerated by OMX_CORE */
                    bFound = OMX_TRUE;

                    eError = OMX_GetHandle(&hComp, (OMX_STRING) cCompEnumName, 0x0, &sCallbacks);
                    if (eError == OMX_ErrorNone)
                    {
                        /* validate the first 4 characters of the name match
                           the OMX standard */
                        if (!strncmp("OMX.", cComponentName, 4))
                        {
                            bNameValid = OMX_TRUE;
                        }

                        eError = OMX_FreeHandle(hComp);

                    }
                    else
                    {
                        OMX_CONF_ErrorToString(eError, szDesc);
                        OMX_OSAL_Trace(OMX_OSAL_TRACE_ERROR, "%s error=0x%X (%s) from OMX_GetHandle\n",
                                       cCompEnumName, eError, szDesc);

                    }

                }

            }
            else if (OMX_ErrorNoMore != eError)
            {
                /* OMX_CORE reported unexpected error other than no more components */
                OMX_CONF_ErrorToString(eError, szDesc);
                OMX_OSAL_Trace(OMX_OSAL_TRACE_ERROR, "unexepected error=0x%X (%s) from OMX_ComponenNameEnum\n",
                               eError, szDesc);
            }
            i++;

        }

        if (OMX_ErrorNoMore == eError)
        {
            /* not an error, so clear the error code */
            eError = OMX_ErrorNone;
        }


OMX_CONF_TEST_BAIL:

        if (OMX_ErrorNone == eError)
        {
            eError = OMX_Deinit();

        }
        else
        {
            OMX_Deinit();
        }

        return eError;
    }
Пример #30
0
bool Component::Deinitialize(string caller)
{
    ofLogVerbose(__func__) << componentName << " by caller: " << caller;
    OMX_ERRORTYPE error = OMX_ErrorNone;

    
    
	if(handle)
	{
		
        flushAll();
		

        error = freeOutputBuffers();
        OMX_TRACE(error);
		freeInputBuffers();
        OMX_TRACE(error);
        
        if((componentName != "OMX.broadcom.egl_render") && (componentName != "OMX.broadcom.video_decode"))
        {
            if(getState() == OMX_StateExecuting)
            {
                setState(OMX_StatePause);
            }
            if(getState() != OMX_StateIdle)
            {
                setState(OMX_StateIdle);
            }
            if(getState() != OMX_StateLoaded)
            {
                setState(OMX_StateLoaded);
            }
        }
		
        if(componentName != "OMX.broadcom.video_decode")
        {
            error = OMX_FreeHandle(handle);
            OMX_TRACE(error); 
        }
		


		handle = NULL;
	}else
    {
        ofLogError(__func__) << "NO HANDLE! caller: " << caller;
    }

	inputPort    = 0;
	outputPort   = 0;
	//componentName = "";

    if(CustomFillBufferDoneHandler)
    {
        CustomFillBufferDoneHandler = NULL;
    }
	if(CustomEmptyBufferDoneHandler)
    {
       CustomEmptyBufferDoneHandler = NULL; 
    }
	

    ofLogVerbose(__func__) << componentName << " END";

	return true;
}