void AnatomyOMXClient::allocateBuffers() {
    OMX_PARAM_PORTDEFINITIONTYPE def;
    InitOMXParams(&def);
    def.nPortIndex = kPortIndexInput;

    OMX_GetParameter(mComponentHandle, OMX_IndexParamPortDefinition, &def);

	OMX_BUFFERHEADERTYPE *pInputHeader;
	for(uint i = 0; i < def.nBufferCountActual; i++ )
	{
		OMX_AllocateBuffer(mComponentHandle, &pInputHeader, 0, this, def.nBufferSize);
		addOMXBufferInfo(kPortIndexInput, pInputHeader);
	}

    InitOMXParams(&def);
    def.nPortIndex = kPortIndexOutput;

    OMX_GetParameter(mComponentHandle, OMX_IndexParamPortDefinition, &def);
	OMX_BUFFERHEADERTYPE *pOutputHeader;
	for(uint i = 0; i < def.nBufferCountActual; i++ )
	{
			OMX_AllocateBuffer(mComponentHandle, &pOutputHeader, 1, this, def.nBufferSize);
			addOMXBufferInfo(kPortIndexOutput, pOutputHeader);
	}
}
Пример #2
0
static void
port_allocate_buffers (GOmxPort *port)
{
    guint i;
    gsize size;

    size = port->buffer_size;

    for (i = 0; i < port->num_buffers; i++)
    {
        if (port->omx_allocate)
        {
            GST_DEBUG_OBJECT (port->core->object, "%d: OMX_AllocateBuffer(), size=%"G_GSIZE_FORMAT, i, size);
            OMX_AllocateBuffer (port->core->omx_handle,
                                &port->buffers[i],
                                port->port_index,
                                NULL,
                                size);
        }
        else
        {
            gpointer buffer_data;
            buffer_data = g_malloc (size);
            GST_DEBUG_OBJECT (port->core->object, "%d: OMX_UseBuffer(), size=%"G_GSIZE_FORMAT, i, size);
            OMX_UseBuffer (port->core->omx_handle,
                           &port->buffers[i],
                           port->port_index,
                           NULL,
                           size,
                           buffer_data);
        }
    }
}
Пример #3
0
void createMinBuffers(int portNumber, OMX_U32 *pBufferSize, OMX_BUFFERHEADERTYPE ***pppBuffers) {
    OMX_PARAM_PORTDEFINITIONTYPE sPortDef;
    OMX_BUFFERHEADERTYPE **ppBuffers;
    int n;
    int nBuffers;

    setHeader(&sPortDef, sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
    sPortDef.nPortIndex = portNumber;
    err = OMX_GetParameter(handle, OMX_IndexParamPortDefinition, &sPortDef);
    if(err != OMX_ErrorNone){
	fprintf(stderr, "Error in getting OMX_PORT_DEFINITION_TYPE parameter\n", 0);
	exit(1);
    }

    *pBufferSize = sPortDef.nBufferSize;
    nBuffers = sPortDef.nBufferCountMin;
    fprintf(stderr, "Port %d has %d buffers of size is %d\n", portNumber, nBuffers, *pBufferSize);

    ppBuffers = malloc(nBuffers * sizeof(OMX_BUFFERHEADERTYPE *));
    if (ppBuffers == NULL) {
	fprintf(stderr, "Can't allocate buffers\n");
	exit(1);
    }

    for (n = 0; n < nBuffers; n++) {
	err = OMX_AllocateBuffer(handle, ppBuffers+n, portNumber, NULL,
				 *pBufferSize);
	if (err != OMX_ErrorNone) {
	    fprintf(stderr, "Error on AllocateBuffer is %d\n", err);
	    exit(1);
	}
    }
    *pppBuffers = ppBuffers;
}
Пример #4
0
status_t OMXNodeInstance::allocateBufferWithBackup(
        OMX_U32 portIndex, const sp<IMemory> &params,
        OMX::buffer_id *buffer) {
    Mutex::Autolock autoLock(mLock);

    BufferMeta *buffer_meta = new BufferMeta(params, true);

    OMX_BUFFERHEADERTYPE *header;

    OMX_ERRORTYPE err = OMX_AllocateBuffer(
            mHandle, &header, portIndex, buffer_meta, params->size());

    if (err != OMX_ErrorNone) {
        ALOGE("OMX_AllocateBuffer failed with error %d (0x%08x)", err, err);

        delete buffer_meta;
        buffer_meta = NULL;

        *buffer = 0;

        return UNKNOWN_ERROR;
    }

    CHECK_EQ(header->pAppPrivate, buffer_meta);

    *buffer = header;

    addActiveBuffer(portIndex, *buffer);

    return OK;
}
OMX_ERRORTYPE prepare_port_buffers(HTEST *hTest, OMX_U32 nPortIndex)
{
    OMX_COMPONENTTYPE *hComponent = NULL;
    OMX_PARAM_PORTDEFINITIONTYPE sPortDef;
    OMX_BUFFERHEADERTYPE *pBufferHdr = NULL;
    OMX_U8 *pBuffer = NULL;
    OMX_U32 i;

    hComponent = hTest->hComponent;
    OMX_INIT_STRUCT(&sPortDef, OMX_PARAM_PORTDEFINITIONTYPE);
    sPortDef.nPortIndex = nPortIndex;
    OMX_GetParameter(hComponent, OMX_IndexParamPortDefinition, &sPortDef);

    for(i=0; i<sPortDef.nBufferCountActual; i++) {
        if(hTest->bAllocater[nPortIndex] == OMX_TRUE) {
            OMX_AllocateBuffer(hComponent, &pBufferHdr, nPortIndex, NULL, sPortDef.nBufferSize);
            printf("Allocate buffer done.\n");
        }
        else {
            pBuffer = (OMX_U8*)FSL_MALLOC(sPortDef.nBufferSize);
            OMX_UseBuffer(hComponent, &pBufferHdr, nPortIndex, NULL, sPortDef.nBufferSize, pBuffer);
            printf("Use buffer done.\n");
        }
        hTest->pBufferHdr[nPortIndex][i] = pBufferHdr;
    }
    hTest->nBufferHdr[nPortIndex] = sPortDef.nBufferCountActual;


    return OMX_ErrorNone;
}
Пример #6
0
void
omx_alloc_buffers(omx_component_t *oc, int port)
{
  OMX_PARAM_PORTDEFINITIONTYPE portdef;

  memset(&portdef, 0, sizeof(portdef));
  portdef.nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE);
  portdef.nVersion.nVersion = OMX_VERSION;
  portdef.nPortIndex = port;

  omxchk(OMX_GetParameter(oc->oc_handle, OMX_IndexParamPortDefinition, &portdef));
  if(portdef.bEnabled != OMX_FALSE || portdef.nBufferCountActual == 0 || portdef.nBufferSize == 0)
    exit(3);

  omxdbg("Allocating buffers for %s:%d\n", oc->oc_name, port);
  omxdbg("  buffer count = %d\n", (int)portdef.nBufferCountActual);
  omxdbg("  buffer size  = %d\n", (int)portdef.nBufferSize);

  omx_send_command(oc, OMX_CommandPortEnable, port, NULL, 0);
  int i;
  for(i = 0; i < portdef.nBufferCountActual; i++) {
    OMX_BUFFERHEADERTYPE *buf;
    omxchk(OMX_AllocateBuffer(oc->oc_handle, &buf, port, NULL, portdef.nBufferSize));
    omxdbg("buf=%p\n", buf);
    buf->pAppPrivate = oc->oc_avail;
    oc->oc_avail = buf;
    oc->oc_avail_bytes += buf->nAllocLen;
  }
  omx_wait_command(oc); // Waits for the OMX_CommandPortEnable command

}
    OMX_ERRORTYPE ResourceExhaustionTest_AllocateAllBuffers(ResourceExhaustionTestContext *pCtxt)
    {
        OMX_ERRORTYPE eError = OMX_ErrorNone;
        OMX_PARAM_PORTDEFINITIONTYPE sPortDef;
        OMX_U32 i, j, k;
        OMX_BUFFERHEADERTYPE *pBufferHdr = NULL;
        BufferList *pBufferListObj;
        BufferList *pTemp;

        /* for all ports */
        for (j = 0; j < NUM_DOMAINS; j++)
        {
            for (i = pCtxt->sPortParam[j].nStartPortNumber;
                    i < pCtxt->sPortParam[j].nStartPortNumber +
                    pCtxt->sPortParam[j].nPorts; i++)
            {

                OMX_CONF_INIT_STRUCT(sPortDef, OMX_PARAM_PORTDEFINITIONTYPE);
                sPortDef.nPortIndex = i;
                OMX_CONF_BAIL_IF_ERROR(OMX_GetParameter(pCtxt->hWComp[pCtxt->nInst],
                                                        OMX_IndexParamPortDefinition,
                                                        (OMX_PTR)&sPortDef));
                if (sPortDef.nBufferCountActual == 0x0 ||
                        sPortDef.nBufferCountActual < sPortDef.nBufferCountMin)
                    OMX_CONF_SET_ERROR_BAIL("Incorrect nBufferCountActual\n", OMX_ErrorUndefined);

                for (k = 0x0; k < sPortDef.nBufferCountActual; k++)
                {
                    pBufferListObj = (BufferList *)OMX_OSAL_Malloc(sizeof(BufferList));
                    if (!pBufferListObj)
                    {
                        OMX_CONF_SET_ERROR_BAIL("Malloc internal list failed\n", OMX_ErrorInsufficientResources);
                    }
                    OMX_CONF_BAIL_IF_ERROR(OMX_AllocateBuffer(pCtxt->hWComp[pCtxt->nInst], &pBufferHdr,
                                           sPortDef.nPortIndex, 0, sPortDef.nBufferSize));
                    pBufferListObj->pNextBuf = NULL;
                    pBufferListObj->pBufHdr = pBufferHdr;

                    if (sPortDef.eDir == OMX_DirInput)
                        pBufferListObj->pBufHdr->nOutputPortIndex = OMX_NOPORT;
                    else
                        pBufferListObj->pBufHdr->nInputPortIndex = OMX_NOPORT;

                    if (pCtxt->pBufferList[pCtxt->nInst] == NULL)
                        pCtxt->pBufferList[pCtxt->nInst] = pBufferListObj;
                    else
                    {
                        pTemp = pCtxt->pBufferList[pCtxt->nInst];
                        while (pTemp->pNextBuf)
                        {
                            pTemp = pTemp->pNextBuf;
                        }
                        pTemp->pNextBuf = pBufferListObj;
                    }
                }
            }
        }
OMX_CONF_TEST_BAIL:
        return eError;
    }
Пример #8
0
status_t OMXNodeInstance::allocateBuffer(
        OMX_U32 portIndex, size_t size, OMX::buffer_id *buffer,
        void **buffer_data) {
    Mutex::Autolock autoLock(mLock);

    BufferMeta *buffer_meta = new BufferMeta(size);

    OMX_BUFFERHEADERTYPE *header;

    OMX_ERRORTYPE err = OMX_AllocateBuffer(
            mHandle, &header, portIndex, buffer_meta, size);

    if (err != OMX_ErrorNone) {
        ALOGE("OMX_AllocateBuffer failed with error %d (0x%08x)", err, err);

        delete buffer_meta;
        buffer_meta = NULL;

        *buffer = 0;

        return UNKNOWN_ERROR;
    }

    CHECK_EQ(header->pAppPrivate, buffer_meta);

    *buffer = header;
    *buffer_data = header->pBuffer;

    addActiveBuffer(portIndex, *buffer);

    return OK;
}
Пример #9
0
OMX_ERRORTYPE Component::allocOutputBuffers()
{
	
    if(!handle) 
    {
        ofLogError(__func__) << getName() << " NO HANDLE";
        return OMX_ErrorNone;
    }
    OMX_ERRORTYPE error = OMX_ErrorNone;
	

	OMX_PARAM_PORTDEFINITIONTYPE portFormat;
	OMX_INIT_STRUCTURE(portFormat);
	portFormat.nPortIndex = outputPort;

	error = OMX_GetParameter(handle, OMX_IndexParamPortDefinition, &portFormat);
    OMX_TRACE(error);
	if(error != OMX_ErrorNone)
	{
		return error;
	}


	if(getState() != OMX_StateIdle)
	{
		if(getState() != OMX_StateLoaded)
		{
			setState(OMX_StateLoaded);
		}
		setState(OMX_StateIdle);
	}

	error = enablePort(outputPort);
    OMX_TRACE(error);
	if(error != OMX_ErrorNone)
	{
		return error;
	}

	for (size_t i = 0; i < portFormat.nBufferCountActual; i++)
	{
		OMX_BUFFERHEADERTYPE *buffer = NULL;
        error = OMX_AllocateBuffer(handle, &buffer, outputPort, NULL, portFormat.nBufferSize);
        OMX_TRACE(error);
        if(error != OMX_ErrorNone)
        {
            return error;
        }
		buffer->nOutputPortIndex = outputPort;
		buffer->nFilledLen       = 0;
		buffer->nOffset          = 0;
		buffer->pAppPrivate      = (void*)i;
        outputBuffers.push_back(buffer);
        outputBuffersAvailable.push(buffer);
	}


	return error;
}
Пример #10
0
OMX_ERRORTYPE omxil_comp::AllocateBuffer(OMX_BUFFERHEADERTYPE **ppBuffer, OMX_U32 nPortIndex, OMX_PTR pAppPrivate, OMX_U32 nSizeBytes)
{
	OMX_ERRORTYPE result;

	result = OMX_AllocateBuffer(comp, ppBuffer, nPortIndex, pAppPrivate, nSizeBytes);
	if (result != OMX_ErrorNone) {
		fprintf(stderr, "OMX_AllocateBuffer failed.\n");
	}

	return result;
}
Пример #11
0
static int startupDecoder(JPEG_DECODER * decoder){
	ilclient_change_component_state(decoder->component,OMX_StateIdle);
	
	OMX_IMAGE_PARAM_PORTFORMATTYPE imagePortFormat;
	memset(&imagePortFormat, 0, sizeof(OMX_IMAGE_PARAM_PORTFORMATTYPE));
	imagePortFormat.nSize = sizeof(OMX_IMAGE_PARAM_PORTFORMATTYPE);
	imagePortFormat.nVersion.nVersion = OMX_VERSION;
	imagePortFormat.nPortIndex = decoder->inPort;
	imagePortFormat.eCompressionFormat = OMX_IMAGE_CodingJPEG;
	OMX_SetParameter(decoder->handle,OMX_IndexParamImagePortFormat, &imagePortFormat);
	
	OMX_PARAM_PORTDEFINITIONTYPE portdef;
	portdef.nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE);
	portdef.nVersion.nVersion = OMX_VERSION;
	portdef.nPortIndex = decoder->inPort;
	OMX_GetParameter(decoder->handle,OMX_IndexParamPortDefinition, &portdef);
	
	portdef.nBufferCountActual = DECODER_BUFFER_NUM;
	
	OMX_SetParameter(decoder->handle,OMX_IndexParamPortDefinition, &portdef);
	
	OMX_SendCommand(decoder->handle, OMX_CommandPortEnable, decoder->inPort, NULL);
	
	int i;
	for (i = 0; i < DECODER_BUFFER_NUM; i++) {
		if (OMX_AllocateBuffer(decoder->handle,
					&(decoder->ppInputBufferHeader[i]),
					decoder->inPort,
					NULL, portdef.nBufferSize) != OMX_ErrorNone) {
			return OMX_IMAGE_ERROR_MEMORY;
		}
	}
	
	int ret = ilclient_wait_for_event(decoder->component, OMX_EventCmdComplete, 
				OMX_CommandPortEnable, 0, decoder->inPort, 0, 0, TIMEOUT_MS);
	if (ret != 0) {
		return OMX_IMAGE_ERROR_PORTS;
	}
	
	ret = OMX_SendCommand(decoder->handle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
	if (ret != OMX_ErrorNone) {
		return OMX_IMAGE_ERROR_EXECUTING;
	}
	
	return OMX_IMAGE_OK;
}
Пример #12
0
static OMX_ERRORTYPE Allocate_Buffer ( OMX_COMPONENTTYPE *avc_dec_handle,
                                       OMX_BUFFERHEADERTYPE  ***pBufHdrs,
                                       OMX_U32 nPortIndex,
                                       long bufCntMin, long bufSize)
{
    DEBUG_PRINT("Inside %s \n", __FUNCTION__);
    OMX_ERRORTYPE error=OMX_ErrorNone;
    long bufCnt=0;

    *pBufHdrs= (OMX_BUFFERHEADERTYPE **)
                   malloc(sizeof(OMX_BUFFERHEADERTYPE*)*bufCntMin);

    for(bufCnt=0; bufCnt < bufCntMin; ++bufCnt) {
        DEBUG_PRINT("\n OMX_AllocateBuffer No %d \n", bufCnt);
        error = OMX_AllocateBuffer(aac_dec_handle, &((*pBufHdrs)[bufCnt]),
                                   nPortIndex, NULL, bufSize);
    }

    return error;
}
static OMX_ERRORTYPE Allocate_Buffer ( OMX_COMPONENTTYPE *avc_dec_handle,
                                       OMX_BUFFERHEADERTYPE  ***pBufHdrs,
                                       OMX_U32 nPortIndex,
                                       long bufCntMin, long bufSize)
{
    DEBUG_PRINT("Inside %s \n", __FUNCTION__);
    OMX_ERRORTYPE error=OMX_ErrorNone;
    long bufCnt=0;
    /* To remove warning for unused variable to keep prototype same */
    (void)avc_dec_handle;
    *pBufHdrs= (OMX_BUFFERHEADERTYPE **)
                   malloc(sizeof(OMX_BUFFERHEADERTYPE*)*bufCntMin);

    for(bufCnt=0; bufCnt < bufCntMin; ++bufCnt) {
        DEBUG_PRINT("\n OMX_AllocateBuffer No %ld \n", bufCnt);
        error = OMX_AllocateBuffer(aac_dec_handle, &((*pBufHdrs)[bufCnt]),
                                   nPortIndex, NULL, bufSize);
    }

    return error;
}
Пример #14
0
OMX_ERRORTYPE TorcOMXPort::CreateBuffers(void)
{
    if (!m_handle)
        return OMX_ErrorUndefined;

    QMutexLocker locker(m_lock);

    OMX_PARAM_PORTDEFINITIONTYPE portdefinition;
    OMX_INITSTRUCTURE(portdefinition);
    portdefinition.nPortIndex = m_port;

    OMX_ERRORTYPE error = OMX_GetParameter(m_handle, OMX_IndexParamPortDefinition, &portdefinition);
    OMX_CHECK(error, m_parent->GetName(), "Failed to get port definition");

    m_alignment = portdefinition.nBufferAlignment;

    for (OMX_U32 i = 0; i < portdefinition.nBufferCountActual; ++i)
    {
        OMX_BUFFERHEADERTYPE *buffer = NULL;
        error = OMX_AllocateBuffer(m_handle, &buffer, m_port, NULL, portdefinition.nBufferSize);
        if (OMX_ErrorNone != error)
        {
            OMX_ERROR(error, m_parent->GetName(), "Failed to allocate buffer");
            return error;
        }

        buffer->pAppPrivate     = (void*)this;
        buffer->nFilledLen      = 0;
        buffer->nOffset         = 0;
        buffer->nInputPortIndex = m_port;

        m_buffers.append(buffer);
        m_availableBuffers.enqueue(buffer);
    }

    LOG(VB_GENERAL, LOG_INFO, QString("%1: Created %2 %3byte buffers")
        .arg(m_parent->GetName()).arg(portdefinition.nBufferCountActual).arg(portdefinition.nBufferSize));

    return OMX_ErrorNone;
}
Пример #15
0
PureOmxBufferData::PureOmxBufferData(const PureOmxPlatformLayer& aPlatformLayer,
                                     const OMX_PARAM_PORTDEFINITIONTYPE& aPortDef)
  : BufferData(nullptr)
  , mPlatformLayer(aPlatformLayer)
  , mPortDef(aPortDef)
{
  LOG_BUF("");

  if (ShouldUseEGLImage()) {
    // TODO
    LOG_BUF("OMX_UseEGLImage() seems available but using it isn't implemented yet.");
  }

  OMX_ERRORTYPE err;
  err = OMX_AllocateBuffer(mPlatformLayer.GetComponent(),
                           &mBuffer,
                           mPortDef.nPortIndex,
                           this,
                           mPortDef.nBufferSize);
  if (err != OMX_ErrorNone) {
    LOG_BUF("Failed to allocate the buffer!: 0x%08x", err);
  }
}
    OMX_ERRORTYPE BufferTest_PortAllocateNumBuffers(
        TEST_CTXTYPE *pCtx,
        TEST_PORTTYPE *pPort,
        OMX_U32 nNumBuffers)
    {
        OMX_ERRORTYPE eError = OMX_ErrorNone;
        OMX_BUFFERHEADERTYPE *pBufHdr;

        while (0x0 != nNumBuffers)
        {
            eError = OMX_AllocateBuffer(pCtx->hWrappedComp, &pBufHdr,
                                        pPort->sPortDef.nPortIndex,
                                        0x0, pPort->sPortDef.nBufferSize);
            OMX_CONF_BAIL_ON_ERROR(eError);
            LIFO_ADD(pPort->pLifo, pBufHdr);
            nNumBuffers--;
        }


OMX_CONF_TEST_BAIL:

        return(eError);
    }
Пример #17
0
// init driver
static int init(sh_video_t *sh){
int i;   

uint8_t *extradata = (uint8_t *)(sh->bih + 1);
    int extradata_size = sh->bih->biSize - sizeof(*sh->bih);
	unsigned char *p = extradata;   
for (i=0;i<extradata_size;i++)
  mp_msg(MSGT_VO,MSGL_ERR,"[%x]",extradata[i]);


        dll_handle=dlopen("libOmxCore.so",RTLD_NOW|RTLD_GLOBAL);
        if (dll_handle){
        pf_init = dlsym( dll_handle, "OMX_Init" );
        pf_deinit = dlsym( dll_handle, "OMX_Deinit" );
        pf_get_handle = dlsym( dll_handle, "OMX_GetHandle" );
        pf_free_handle = dlsym( dll_handle, "OMX_FreeHandle" );
        pf_component_enum = dlsym( dll_handle, "OMX_ComponentNameEnum" );
        pf_get_roles_of_component = dlsym( dll_handle, "OMX_GetRolesOfComponent" );
        if( !pf_init || !pf_deinit || !pf_get_handle || !pf_free_handle ||
        !pf_component_enum || !pf_get_roles_of_component )
        {
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","Error in OMX");
        }
        else
        {
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","Success in OMX");
        omx_error = pf_init();
        if(omx_error != OMX_ErrorNone)
        {
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","OMX Init Failed");
        return 0;
 	}
        while (1){
        omx_error=pf_component_enum(psz_name, OMX_MAX_STRINGNAME_SIZE, i);
        if(omx_error != OMX_ErrorNone) break;
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","Component %d,%s",i,psz_name);
        omx_error = pf_get_roles_of_component(psz_name, &no_of_roles, NULL);
        if (omx_error != OMX_ErrorNone) {
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","No Role for Component %s",psz_name);
        }
        else {
        if(no_of_roles == 0) {
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","No Role for Component -2  %s",psz_name);
        }
        else
        {
                string_of_roles = malloc(no_of_roles * sizeof(OMX_STRING));
                for (index1 = 0; index1 < no_of_roles; index1++)
                {
                        *(string_of_roles + index1) = malloc(no_of_roles * OMX_MAX_STRINGNAME_SIZE);
                }
                omx_error = pf_get_roles_of_component(psz_name, &no_of_roles, string_of_roles);
                if (omx_error == OMX_ErrorNone && string_of_roles!=NULL) {
                for (index1 = 0; index1 < no_of_roles; index1++) {
                __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","The role %i for the component:  %s",(index1+1),*(string_of_roles+index1));
                }
                }
                else    {
                __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","Error getting role");
                }
        }
        }
        i++;
        }
        omx_error=pf_get_handle( &omx_handle, "OMX.qcom.video.decoder.avc\0",NULL,&callbacks);
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","Get Handle %s",ErrorToString(omx_error));
	if (omx_handle){
	input_port_def.nPortIndex = 0;
	 omx_error = OMX_GetParameter(omx_handle,
                               OMX_IndexParamPortDefinition,
                               &input_port_def);
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","GetPortDefination %s",ErrorToString(omx_error));


        input_port_def.format.video.eCompressionFormat = OMX_VIDEO_CodingAVC;     
	input_port_def.format.video.nFrameWidth  = sh->disp_w;
        input_port_def.format.video.nFrameHeight = sh->disp_h;
        omx_error = OMX_SetParameter(omx_handle,
                               OMX_IndexParamPortDefinition,
                               &input_port_def);
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","SetParameter %s",ErrorToString(omx_error));
	
	omx_error = OMX_SendCommand(omx_handle, OMX_CommandPortEnable, 1, NULL);
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","PortEnable %s",ErrorToString(omx_error));
	
	outBufferParseVideo[0] = outBufferParseVideo[1] = NULL;
	omx_error = OMX_SendCommand( omx_handle, OMX_CommandStateSet, OMX_StateIdle, 0 );
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","StateIdle %s",ErrorToString(omx_error));
	sleep(1);
	omx_error = OMX_SendCommand( omx_handle, OMX_CommandStateSet, OMX_StateLoaded, 0 );
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","StateLoaded %s",ErrorToString(omx_error));

	omx_error = OMX_AllocateBuffer(omx_handle, &outBufferParseVideo[0], 0, NULL,16384);
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","AllocateBuffer %s",ErrorToString(omx_error));
	
	omx_error = OMX_AllocateBuffer(omx_handle, &outBufferParseVideo[1], 0, NULL,16384);
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","AllocateBuffer %s",ErrorToString(omx_error));
/*	omx_error = OMX_UseBuffer(omx_handle, &inBufferVideoDec[0], 0, NULL, 16384, outBufferParseVideo[0]->pBuffer);
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","UseBuffer 1%s",ErrorToString(omx_error));
	omx_error = OMX_UseBuffer(omx_handle, &inBufferVideoDec[1], 0, NULL, 16384, outBufferParseVideo[1]->pBuffer);
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","UseBuffer 2%s",ErrorToString(omx_error));*/
	omx_error = OMX_AllocateBuffer(omx_handle, &outBufferVideoDec[0], 1, NULL, 16384);
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","AllocateBuffer Video 1%s",ErrorToString(omx_error));
	omx_error = OMX_AllocateBuffer(omx_handle, &outBufferVideoDec[1], 1, NULL, 16384);
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","AllocateBuffer Video 2%s",ErrorToString(omx_error));
	omx_error = OMX_SendCommand(omx_handle, OMX_CommandStateSet,OMX_StateExecuting, 0);
	sleep(1);
	outBufferParseVideo[0]->nFilledLen = extradata_size;
	memcpy(outBufferParseVideo[0]->pBuffer, extradata, extradata_size);
	omx_error=OMX_EmptyThisBuffer(omx_handle, outBufferParseVideo[0]);
        if (omx_error != OMX_ErrorNone) {
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","Error %s",ErrorToString(omx_error));
        }
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","Error %s",ErrorToString(omx_error));









        }
	}
        }
        else
        __android_log_print(ANDROID_LOG_ERROR  , "MPlayer","Unable to open OMX dll");
        

  return 1;
}
Пример #18
0
static int Open(vlc_object_t *p_this)
{
    vout_display_t *vd = (vout_display_t *)p_this;
    vout_display_t *p_dec = vd;
    char ppsz_components[MAX_COMPONENTS_LIST_SIZE][OMX_MAX_STRINGNAME_SIZE];
    picture_t** pictures = NULL;
    OMX_PARAM_PORTDEFINITIONTYPE *def;

    static OMX_CALLBACKTYPE callbacks =
        { OmxEventHandler, OmxEmptyBufferDone, OmxFillBufferDone };

    if (InitOmxCore(p_this) != VLC_SUCCESS)
        return VLC_EGENERIC;

    int components = CreateComponentsList(p_this, "iv_renderer", ppsz_components);
    if (components <= 0) {
        DeinitOmxCore();
        return VLC_EGENERIC;
    }

    /* Allocate structure */
    vout_display_sys_t *p_sys = (struct vout_display_sys_t*) calloc(1, sizeof(*p_sys));
    if (!p_sys) {
        DeinitOmxCore();
        return VLC_ENOMEM;
    }

    vd->sys     = p_sys;
    strcpy(p_sys->psz_component, ppsz_components[0]);

    /* Load component */
    OMX_ERRORTYPE omx_error = pf_get_handle(&p_sys->omx_handle,
                                            p_sys->psz_component, vd, &callbacks);
    CHECK_ERROR(omx_error, "OMX_GetHandle(%s) failed (%x: %s)",
                p_sys->psz_component, omx_error, ErrorToString(omx_error));

    InitOmxEventQueue(&p_sys->event_queue);
    OMX_FIFO_INIT(&p_sys->port.fifo, pOutputPortPrivate);
    p_sys->port.b_direct = false;
    p_sys->port.b_flushed = true;

    OMX_PORT_PARAM_TYPE param;
    OMX_INIT_STRUCTURE(param);
    omx_error = OMX_GetParameter(p_sys->omx_handle, OMX_IndexParamVideoInit, &param);
    CHECK_ERROR(omx_error, "OMX_GetParameter(OMX_IndexParamVideoInit) failed (%x: %s)",
                omx_error, ErrorToString(omx_error));

    p_sys->port.i_port_index = param.nStartPortNumber;
    p_sys->port.b_valid = true;
    p_sys->port.omx_handle = p_sys->omx_handle;

    def = &p_sys->port.definition;
    OMX_INIT_STRUCTURE(*def);
    def->nPortIndex = p_sys->port.i_port_index;
    omx_error = OMX_GetParameter(p_sys->omx_handle, OMX_IndexParamPortDefinition, def);
    CHECK_ERROR(omx_error, "OMX_GetParameter(OMX_IndexParamPortDefinition) failed (%x: %s)",
                omx_error, ErrorToString(omx_error));

#define ALIGN(x, y) (((x) + ((y) - 1)) & ~((y) - 1))

    def->format.video.nFrameWidth = vd->fmt.i_width;
    def->format.video.nFrameHeight = vd->fmt.i_height;
    def->format.video.nStride = 0;
    def->format.video.nSliceHeight = 0;
    p_sys->port.definition.format.video.eColorFormat = OMX_COLOR_FormatYUV420PackedPlanar;

    if (!strcmp(p_sys->psz_component, "OMX.broadcom.video_render")) {
        def->format.video.nSliceHeight = ALIGN(def->format.video.nFrameHeight, 16);
    }

    omx_error = OMX_SetParameter(p_sys->omx_handle, OMX_IndexParamPortDefinition, &p_sys->port.definition);
    CHECK_ERROR(omx_error, "OMX_SetParameter(OMX_IndexParamPortDefinition) failed (%x: %s)",
                omx_error, ErrorToString(omx_error));
    OMX_GetParameter(p_sys->omx_handle, OMX_IndexParamPortDefinition, &p_sys->port.definition);

    if (def->format.video.nStride < (int) def->format.video.nFrameWidth)
        def->format.video.nStride = def->format.video.nFrameWidth;
    if (def->format.video.nSliceHeight < def->format.video.nFrameHeight)
        def->format.video.nSliceHeight = def->format.video.nFrameHeight;

    p_sys->port.pp_buffers =
            malloc(p_sys->port.definition.nBufferCountActual *
                   sizeof(OMX_BUFFERHEADERTYPE*));
    p_sys->port.i_buffers = p_sys->port.definition.nBufferCountActual;

    omx_error = OMX_SendCommand(p_sys->omx_handle, OMX_CommandStateSet, OMX_StateIdle, 0);
    CHECK_ERROR(omx_error, "OMX_CommandStateSet Idle failed (%x: %s)",
                omx_error, ErrorToString(omx_error));

    unsigned int i;
    for (i = 0; i < p_sys->port.i_buffers; i++) {
        omx_error = OMX_AllocateBuffer(p_sys->omx_handle, &p_sys->port.pp_buffers[i],
                                       p_sys->port.i_port_index, 0,
                                       p_sys->port.definition.nBufferSize);
        if (omx_error != OMX_ErrorNone)
            break;
        OMX_FIFO_PUT(&p_sys->port.fifo, p_sys->port.pp_buffers[i]);
    }
    if (omx_error != OMX_ErrorNone) {
        p_sys->port.i_buffers = i;
        for (i = 0; i < p_sys->port.i_buffers; i++)
            OMX_FreeBuffer(p_sys->omx_handle, p_sys->port.i_port_index, p_sys->port.pp_buffers[i]);
        msg_Err(vd, "OMX_AllocateBuffer failed (%x: %s)",
                omx_error, ErrorToString(omx_error));
        goto error;
    }

    omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
    CHECK_ERROR(omx_error, "Wait for Idle failed (%x: %s)",
                omx_error, ErrorToString(omx_error));

    omx_error = OMX_SendCommand(p_sys->omx_handle, OMX_CommandStateSet,
                                OMX_StateExecuting, 0);
    CHECK_ERROR(omx_error, "OMX_CommandStateSet Executing failed (%x: %s)",
                omx_error, ErrorToString(omx_error));
    omx_error = WaitForSpecificOmxEvent(&p_sys->event_queue, OMX_EventCmdComplete, 0, 0, 0);
    CHECK_ERROR(omx_error, "Wait for Executing failed (%x: %s)",
                omx_error, ErrorToString(omx_error));

    if (!strcmp(p_sys->psz_component, "OMX.broadcom.video_render")) {
        OMX_CONFIG_DISPLAYREGIONTYPE config_display;
        OMX_INIT_STRUCTURE(config_display);
        config_display.nPortIndex = p_sys->port.i_port_index;

        config_display.set = OMX_DISPLAY_SET_SRC_RECT;
        config_display.src_rect.width = vd->cfg->display.width;
        config_display.src_rect.height = vd->cfg->display.height;
        OMX_SetConfig(p_sys->omx_handle, OMX_IndexConfigDisplayRegion, &config_display);
        config_display.set = OMX_DISPLAY_SET_FULLSCREEN;
        config_display.fullscreen = OMX_TRUE;
        OMX_SetConfig(p_sys->omx_handle, OMX_IndexConfigDisplayRegion, &config_display);

        UpdateDisplaySize(vd, vd->cfg);
    }


    /* Setup chroma */
    video_format_t fmt = vd->fmt;

    fmt.i_chroma = VLC_CODEC_I420;
    video_format_FixRgb(&fmt);

    /* Setup vout_display */
    vd->fmt     = fmt;
    vd->pool    = Pool;
    vd->display = Display;
    vd->control = Control;
    vd->prepare = NULL;
    vd->manage  = NULL;

    /* Create the associated picture */
    pictures = calloc(p_sys->port.i_buffers, sizeof(*pictures));
    if (!pictures)
        goto error;
    for (unsigned int i = 0; i < p_sys->port.i_buffers; i++) {
        picture_sys_t *picsys = malloc(sizeof(*picsys));
        if (unlikely(picsys == NULL))
            goto error;
        picsys->sys = p_sys;

        picture_resource_t resource = { .p_sys = picsys };

        picture_t *picture = picture_NewFromResource(&fmt, &resource);
        if (unlikely(picture == NULL))
        {
            free(picsys);
            goto error;
        }
        pictures[i] = picture;
    }

    /* Wrap it into a picture pool */
    picture_pool_configuration_t pool_cfg;
    memset(&pool_cfg, 0, sizeof(pool_cfg));
    pool_cfg.picture_count = p_sys->port.i_buffers;
    pool_cfg.picture       = pictures;
    pool_cfg.lock          = LockSurface;
    pool_cfg.unlock        = UnlockSurface;

    p_sys->pool = picture_pool_NewExtended(&pool_cfg);
    if (!p_sys->pool) {
        for (unsigned int i = 0; i < p_sys->port.i_buffers; i++)
            picture_Release(pictures[i]);
        goto error;
    }

    /* Fix initial state */
    vout_display_SendEventFullscreen(vd, true);

    free(pictures);
    return VLC_SUCCESS;

error:
    free(pictures);
    Close(p_this);
    return VLC_EGENERIC;
}
int encoder_init(struct picture_t *info,int fps,int bright,int video_bitrate)
{
	//tem_width=info->width;
	bcm_host_init();
	
    OMX_ERRORTYPE r;

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

    // Init context
    
    memset(&ctx, 0, sizeof(ctx));
    if(vcos_semaphore_create(&ctx.handler_lock, "handler_lock", 1) != VCOS_SUCCESS) {
        die("Failed to create handler lock semaphore");
    }
	
    // Init component handles
    OMX_CALLBACKTYPE callbacks;
    memset(&ctx, 0, sizeof(callbacks));
    callbacks.EventHandler   = event_handler;
    callbacks.FillBufferDone = fill_output_buffer_done_handler;

    init_component_handle("camera", &ctx.camera , &ctx, &callbacks);
    init_component_handle("video_encode", &ctx.encoder, &ctx, &callbacks);
    init_component_handle("null_sink", &ctx.null_sink, &ctx, &callbacks);
    
    /*
    OMX_CALLBACKTYPE callbacks1;
    memset(&ctx, 0, sizeof(callbacks1));
    callbacks1.EventHandler   = event_handler;
    callbacks1.FillBufferDone = fill_camera_output_buffer_done_handler;
*/
    init_component_handle("camera", &ctx.camera , &ctx, &callbacks);
	//===============change^^^^================
	
    //say("Configuring camera...");

    //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);

    // 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  = info->width;
    camera_portdef.format.video.nFrameHeight = info->height;
    camera_portdef.format.video.xFramerate   = fps << 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 = bright;
    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.nSensitivity = CAM_EXPOSURE_ISO_SENSITIVITY;
    if((r = OMX_SetConfig(ctx.camera, OMX_IndexConfigCommonExposureValue, &exposure_value)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set camera exposure value configuration");
    }
    // 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_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");
    }
    // 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 encoder...");

    //say("Default port definition for encoder input port 200");
    dump_port(ctx.encoder, 200, OMX_TRUE);
    //say("Default port definition for encoder output port 201");
    dump_port(ctx.encoder, 201, OMX_TRUE);

    // Encoder input port definition is done automatically upon tunneling

    // Configure video format emitted by encoder output port
    OMX_PARAM_PORTDEFINITIONTYPE encoder_portdef;
    OMX_INIT_STRUCTURE(encoder_portdef);
    encoder_portdef.nPortIndex = 201;
    if((r = OMX_GetParameter(ctx.encoder, OMX_IndexParamPortDefinition, &encoder_portdef)) != OMX_ErrorNone) {
        omx_die(r, "Failed to get port definition for encoder output port 201");
    }
    // Copy some of the encoder output port configuration
    // from camera output port
    encoder_portdef.format.video.nFrameWidth  = camera_portdef.format.video.nFrameWidth;
    encoder_portdef.format.video.nFrameHeight = camera_portdef.format.video.nFrameHeight;
    encoder_portdef.format.video.xFramerate   = camera_portdef.format.video.xFramerate;
    encoder_portdef.format.video.nStride      = camera_portdef.format.video.nStride;
    // Which one is effective, this or the configuration just below?
    encoder_portdef.format.video.nBitrate     = video_bitrate;
    if((r = OMX_SetParameter(ctx.encoder, OMX_IndexParamPortDefinition, &encoder_portdef)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set port definition for encoder output port 201");
    }
    // Configure bitrate
    OMX_VIDEO_PARAM_BITRATETYPE bitrate;
    OMX_INIT_STRUCTURE(bitrate);
    bitrate.eControlRate = OMX_Video_ControlRateVariable;
    bitrate.nTargetBitrate = encoder_portdef.format.video.nBitrate;
    bitrate.nPortIndex = 201;
    if((r = OMX_SetParameter(ctx.encoder, OMX_IndexParamVideoBitrate, &bitrate)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set bitrate for encoder output port 201");
    }
    // Configure format
    OMX_VIDEO_PARAM_PORTFORMATTYPE format;
    OMX_INIT_STRUCTURE(format);
    format.nPortIndex = 201;
    format.eCompressionFormat = OMX_VIDEO_CodingAVC;
    if((r = OMX_SetParameter(ctx.encoder, OMX_IndexParamVideoPortFormat, &format)) != OMX_ErrorNone) {
        omx_die(r, "Failed to set video format for encoder output port 201");
    }
	
	OMX_CONFIG_PORTBOOLEANTYPE inlineHeader;
    OMX_INIT_STRUCTURE(inlineHeader);
    inlineHeader.nPortIndex = 201;
    inlineHeader.bEnabled = OMX_TRUE; 
    if((r = OMX_SetParameter(ctx.encoder, OMX_IndexParamBrcmVideoAVCInlineHeaderEnable, &inlineHeader)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch on inlineHeader on video encoder output port 201");
    }
	
	 OMX_VIDEO_PARAM_AVCTYPE avc_st;
  OMX_INIT_STRUCTURE (avc_st);
  avc_st.nPortIndex = 201;
  if ((r = OMX_GetParameter (ctx.encoder,
      OMX_IndexParamVideoAvc, &avc_st))){
    omx_die(r, "Failed to switch on avc_st on video encoder output port 201");
  }
  avc_st.nPFrames = VIDEO_FRAMERATE-1;
  if ((r = OMX_SetParameter (ctx.encoder,
      OMX_IndexParamVideoAvc, &avc_st))){
    omx_die(r, "Failed to switch on avc_st on video encoder output port 201");
  }
	

    //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.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 encoder input port
    //say("Setting up tunnel from camera video output port 71 to encoder input port 200...");
    if((r = OMX_SetupTunnel(ctx.camera, 71, ctx.encoder, 200)) != OMX_ErrorNone) {
        omx_die(r, "Failed to setup tunnel between camera video output port 71 and encoder input port 200");
    }

    // Switch components to idle state
    //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 encoder component to idle...");
    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);
    //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.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.encoder, OMX_CommandPortEnable, 200, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to enable encoder input port 200");
    }
    block_until_port_changed(ctx.encoder, 200, OMX_TRUE);
    if((r = OMX_SendCommand(ctx.encoder, OMX_CommandPortEnable, 201, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to enable encoder output port 201");
    }
    block_until_port_changed(ctx.encoder, 201, 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 and encoder output buffer,
    // buffers for tunneled ports are allocated internally by OMX
    //say("Allocating buffers...");
    OMX_INIT_STRUCTURE(camera_portdef);
    camera_portdef.nPortIndex = 73;
    if((r = OMX_GetParameter(ctx.camera, OMX_IndexParamPortDefinition, &camera_portdef)) != OMX_ErrorNone) {
        omx_die(r, "Failed to get port definition for camera input port 73");
    }
    if((r = OMX_AllocateBuffer(ctx.camera, &ctx.camera_ppBuffer_in, 73, NULL, camera_portdef.nBufferSize)) != OMX_ErrorNone) {
        omx_die(r, "Failed to allocate buffer for camera input port 73");
    }
    /*
    camera_portdef.nPortIndex = 71;
    if((r = OMX_AllocateBuffer(ctx.camera, &ctx.camera_ppBuffer_out, 71, NULL, camera_portdef.nBufferSize)) != OMX_ErrorNone) {
        omx_die(r, "Failed to allocate buffer for camera output port 71");
    }
    */
    OMX_INIT_STRUCTURE(encoder_portdef);
    encoder_portdef.nPortIndex = 201;
    if((r = OMX_GetParameter(ctx.encoder, OMX_IndexParamPortDefinition, &encoder_portdef)) != OMX_ErrorNone) {
        omx_die(r, "Failed to get port definition for encoder output port 201");
    }
    if((r = OMX_AllocateBuffer(ctx.encoder, &ctx.encoder_ppBuffer_out, 201, NULL, encoder_portdef.nBufferSize)) != OMX_ErrorNone) {
        omx_die(r, "Failed to allocate buffer for encoder output port 201");
    }

    // 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.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 encoder component to executing...");
    if((r = OMX_SendCommand(ctx.encoder, OMX_CommandStateSet, OMX_StateExecuting, NULL)) != OMX_ErrorNone) {
        omx_die(r, "Failed to switch state of the encoder component to executing");
    }
    block_until_state_changed(ctx.encoder, 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);


    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 encoder input port 200");
    dump_port(ctx.encoder, 200, OMX_FALSE);
    //say("Configured port definition for encoder output port 201");
    dump_port(ctx.encoder, 201, OMX_FALSE);
    //say("Configured port definition for null sink input port 240");
    dump_port(ctx.null_sink, 240, OMX_FALSE);

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

    return 1;
}
Пример #20
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;
}
Пример #21
0
int main(int argc, char** argv) {

	OMX_PORT_PARAM_TYPE param;
	OMX_PARAM_PORTDEFINITIONTYPE sPortDef;
	OMX_AUDIO_PORTDEFINITIONTYPE sAudioPortDef;
	OMX_AUDIO_PARAM_PORTFORMATTYPE sAudioPortFormat;
	OMX_AUDIO_PARAM_PCMMODETYPE sPCMMode;
	OMX_BUFFERHEADERTYPE **inBuffers[2];

	char *componentName = "OMX.broadcom.video_render";
	unsigned char name[OMX_MAX_STRINGNAME_SIZE];
	OMX_UUIDTYPE uid;
	int startPortNumber;
	int nPorts;
	int i, n;

	bcm_host_init();

	fprintf(stderr, "Thread id is %p\n", pthread_self());
	if(argc < 2){
		display_help(argv);
		exit(1);
	}

	fd = open(argv[1], O_RDONLY);
	if(fd < 0){
		perror("Error opening input file\n");
		exit(1);
	}
	filesize = getFileSize(fd);


	err = OMX_Init();
	if(err != OMX_ErrorNone) {
		fprintf(stderr, "OMX_Init() failed\n", 0);
		exit(1);
	}
	/** Ask the core for a handle to the audio render component
	 */
	err = OMX_GetHandle(&handle, componentName, NULL /*app private data */, &callbacks);
	if(err != OMX_ErrorNone) {
		fprintf(stderr, "OMX_GetHandle failed\n", 0);
		exit(1);
	}
	err = OMX_GetComponentVersion(handle, name, &compVersion, &specVersion, &uid);
	if(err != OMX_ErrorNone) {
		fprintf(stderr, "OMX_GetComponentVersion failed\n", 0);
		exit(1);
	}

	/** disable other ports */
	disablePort(OMX_IndexParamOtherInit);

	/** Get audio port information */
	setHeader(&param, sizeof(OMX_PORT_PARAM_TYPE));
	err = OMX_GetParameter(handle, OMX_IndexParamVideoInit, &param);
	if(err != OMX_ErrorNone){
		fprintf(stderr, "Error in getting OMX_PORT_PARAM_TYPE parameter\n", 0);
		exit(1);
	}
	startPortNumber = ((OMX_PORT_PARAM_TYPE)param).nStartPortNumber;
	nPorts = ((OMX_PORT_PARAM_TYPE)param).nPorts;
	if (nPorts > 2) {
		fprintf(stderr, "Image device has more than one port\n");
		exit(1);
	}

	for (i = 0; i < nPorts; i++) {
		/* Get and check port information */
		setHeader(&sPortDef, sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
		sPortDef.nPortIndex = startPortNumber + i;
		err = OMX_GetParameter(handle, OMX_IndexParamPortDefinition, &sPortDef);

		if(err != OMX_ErrorNone) {
			fprintf(stderr, "Error in getting OMX_PORT_DEFINITION_TYPE parameter\n", 0);
			exit(1);
		}
		if (sPortDef.eDomain != OMX_PortDomainVideo) {
			fprintf(stderr, "Port %d is not a video port\n", sPortDef.nPortIndex);
			exit(1);
		}

		if (sPortDef.eDir == OMX_DirInput)
			fprintf(stdout, "Port %d is an input port\n", sPortDef.nPortIndex);
		else
			fprintf(stdout, "Port %d is an output port\n", sPortDef.nPortIndex);

		if (sPortDef.format.video.eColorFormat == OMX_COLOR_FormatYUV420PackedPlanar)
			fprintf(stderr, "Port color Format is YUV420PackedPlanar\n");
		else
			fprintf(stderr, "Port has unknown color format\n");

		/* Set Image Format -- FIXME: hardcoded */
		sPortDef.format.video.nFrameWidth = 1920;
		sPortDef.format.video.nFrameHeight = 1080;
		sPortDef.format.video.nStride =
			ALIGN(sPortDef.format.video.nFrameWidth, 32);
		sPortDef.format.image.nSliceHeight =
			ALIGN(sPortDef.format.video.nFrameHeight, 16);
		sPortDef.nBufferSize = sPortDef.format.image.nStride *
			sPortDef.format.image.nSliceHeight * 3 / 2;

		/* Create minimum number of buffers for the port */
		nBuffers = sPortDef.nBufferCountActual = sPortDef.nBufferCountMin;
		fprintf(stderr, "Number of bufers is %d\n", nBuffers);
		err = OMX_SetParameter(handle, OMX_IndexParamPortDefinition, &sPortDef);
		if(err != OMX_ErrorNone){
			fprintf(stderr, "Error in setting OMX_PORT_PARAM_TYPE parameter\n", 0);
			exit(1);
		}
		if (sPortDef.bEnabled) {
			fprintf(stderr, "Port %d is enabled\n", sPortDef.nPortIndex);
		} else {
			fprintf(stderr, "Port %d is not enabled\n", sPortDef.nPortIndex);
		}
	}

	/* call to put state into idle before allocating buffers */
	printf("OMX_CommandStateSet, OMX_StateIdle\n");
	err = OMX_SendCommand(handle, OMX_CommandStateSet, OMX_StateIdle, NULL);
	if (err != OMX_ErrorNone) {
		fprintf(stderr, "Error on setting state to idle\n");
		exit(1);
	}

	for (i = 0; i < nPorts; i++) {
		/* Get and check port information */
		setHeader(&sPortDef, sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
		sPortDef.nPortIndex = startPortNumber + i;
		err = OMX_GetParameter(handle, OMX_IndexParamPortDefinition, &sPortDef);

		if(err != OMX_ErrorNone) {
			fprintf(stderr, "Error in getting OMX_PORT_DEFINITION_TYPE parameter\n", 0);
			exit(1);
		}

		if (!sPortDef.bEnabled) {
			printf("OMX_CommandPortEnable, %d\n", startPortNumber);
			err = OMX_SendCommand(handle, OMX_CommandPortEnable, startPortNumber, NULL);
			if (err != OMX_ErrorNone) {
				fprintf(stderr, "Error on setting port to enabled\n");
				exit(1);
			}
		}
	}

	/* Configure buffers for the port */
	for (i = 0; i < nPorts; i++) {
		setHeader(&sPortDef, sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
		sPortDef.nPortIndex = startPortNumber + i;
		err = OMX_GetParameter(handle, OMX_IndexParamPortDefinition, &sPortDef);

		nBufferSize = sPortDef.nBufferSize;
		fprintf(stderr, "Port %d has %d buffers of size %d\n", sPortDef.nPortIndex,
				nBuffers, nBufferSize);

		inBuffers[i] = malloc(nBuffers * sizeof(OMX_BUFFERHEADERTYPE *));
		if (inBuffers[i] == NULL) {
			fprintf(stderr, "Can't allocate buffers\n");
			exit(1);
		}

		for (n = 0; n < nBuffers; n++) {
			err = OMX_AllocateBuffer(handle, inBuffers[i] + n, startPortNumber + i, NULL,
						 nBufferSize);
			if (err != OMX_ErrorNone) {
				fprintf(stderr, "Error on AllocateBuffer in 1%i\n", err);
				exit(1);
			}
		}
	}

	printf("Transition to Idle\n");
	/* Make sure we've reached Idle state */
	waitFor(OMX_StateIdle);

	printf("Transition to Executing\n");
	/* Now try to switch to Executing state */
	err = OMX_SendCommand(handle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
	if(err != OMX_ErrorNone){
		exit(1);
	}

	/* One buffer is the minimum for Broadcom component, so use that */
	pEmptyBuffer = inBuffers[0][0];
	emptyState = 1;
	/* Fill and empty buffer */
	for (;;) {
		int data_read = read(fd, pEmptyBuffer->pBuffer, nBufferSize);
		pEmptyBuffer->nFilledLen = data_read;
		pEmptyBuffer->nOffset = 0;
		filesize -= data_read;
		if (filesize <= 0) {
			pEmptyBuffer->nFlags = OMX_BUFFERFLAG_EOS;
		}
		fprintf(stderr, "Emptying again buffer %p %d bytes, %d to go\n", pEmptyBuffer, data_read, filesize);
		err = OMX_EmptyThisBuffer(handle, pEmptyBuffer);
		waitForEmpty();
		fprintf(stderr, "Waited for empty\n");
		if (bEOS) {
			fprintf(stderr, "Exiting loop\n");
			break;
		}
	}
	fprintf(stderr, "Buffers emptied\n");
	exit(0);
}
Пример #22
0
static void omx_init(audio_backend_pull_callback_t pull_callback)
{
	OMX_ERRORTYPE error;

	error = OMX_Init();
	if(error != OMX_ErrorNone)
	{
		fprintf(stderr, "OMX: OMX_Init() failed. Error 0x%X\n", error);
		return;
	}

	// Initialize settings
	latency_max = settings.omx.Audio_Latency;
	buffer_size = settings.aica.BufferSize * 4;
	buffer_count = 2 + OUTPUT_FREQ * latency_max / (buffer_size * 1000);

	OMX_CALLBACKTYPE callbacks;
	callbacks.EventHandler = EventHandler;
	callbacks.EmptyBufferDone = EmptyBufferDone;
	callbacks.EmptyBufferDone = FillBufferDone;

	error = OMX_GetHandle(&omx_handle, (OMX_STRING)"OMX.broadcom.audio_render", NULL, &callbacks);
	if(error != OMX_ErrorNone)
	{
		fprintf(stderr, "OMX: OMX_GetHandle() failed. Error 0x%X\n", error);
		return;
	}

	OMX_PARAM_PORTDEFINITIONTYPE param;
	memset(&param, 0, sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
	param.nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE);
	param.nVersion.nVersion = OMX_VERSION;
	param.nPortIndex = PORT_INDEX;
	param.nBufferSize = buffer_size;
	param.nBufferCountActual = buffer_count;
	param.format.audio.eEncoding = OMX_AUDIO_CodingPCM;

	error = OMX_SetParameter(omx_handle, OMX_IndexParamPortDefinition, &param);
	if(error != OMX_ErrorNone)
		fprintf(stderr, "OMX: failed to set OMX_IndexParamPortDefinition. Error 0x%X\n", error);

	OMX_AUDIO_PARAM_PCMMODETYPE pcm;
	memset(&pcm, 0, sizeof(OMX_AUDIO_PARAM_PCMMODETYPE));
	pcm.nSize = sizeof(OMX_AUDIO_PARAM_PCMMODETYPE);
	pcm.nVersion.nVersion = OMX_VERSION;
	pcm.nPortIndex = PORT_INDEX;
	pcm.nChannels = 2;
	pcm.eNumData = OMX_NumericalDataSigned;
	pcm.eEndian = OMX_EndianLittle;
	pcm.nSamplingRate = OUTPUT_FREQ;
	pcm.bInterleaved = OMX_TRUE;
	pcm.nBitPerSample = 16;
	pcm.ePCMMode = OMX_AUDIO_PCMModeLinear;
	pcm.eChannelMapping[1] = OMX_AUDIO_ChannelRF;
	pcm.eChannelMapping[0] = OMX_AUDIO_ChannelLF;

	error = OMX_SetParameter(omx_handle, OMX_IndexParamAudioPcm, &pcm);
	if(error != OMX_ErrorNone)
		fprintf(stderr, "OMX: failed to set OMX_IndexParamAudioPcm. Error 0x%X\n", error);

	// Disable all ports
	error = OMX_SendCommand(omx_handle, OMX_CommandPortDisable, PORT_INDEX, NULL);
	if(error != OMX_ErrorNone)
		fprintf(stderr, "OMX: failed to do OMX_CommandPortDisable. Error 0x%X\n", error);

	OMX_PORT_PARAM_TYPE param2;
	memset(&param2, 0, sizeof(OMX_PORT_PARAM_TYPE));
	param2.nSize = sizeof(OMX_PORT_PARAM_TYPE);
	param2.nVersion.nVersion = OMX_VERSION;
	error = OMX_GetParameter(omx_handle, OMX_IndexParamOtherInit, &param2);
	if(error != OMX_ErrorNone)
	{
		fprintf(stderr, "OMX: failed to get OMX_IndexParamOtherInit. Error 0x%X\n", error);
	}
	else
	{
		for(u32 i = 0; i < param2.nPorts; i++)
		{
			u32 port = param2.nStartPortNumber + i;
			error = OMX_SendCommand(omx_handle, OMX_CommandPortDisable, port, NULL);
			if(error != OMX_ErrorNone)
				fprintf(stderr, "OMX: failed to do OMX_CommandPortDisable on port %u. Error 0x%X\n", port, error);
		}
	}

	// Go into idle state
	error = OMX_SendCommand(omx_handle, OMX_CommandStateSet, OMX_StateIdle, NULL);
	if(error != OMX_ErrorNone)
	{
		fprintf(stderr, "OMX: failed to set OMX_CommandStateSet. Error 0x%X\n", error);
		return;
	}
	omx_wait_for_state(OMX_StateIdle);

	// Check if we're in a state able to recieve buffers
	OMX_STATETYPE state;
	error = OMX_GetState(omx_handle, &state);
	if(error != OMX_ErrorNone || !(state == OMX_StateIdle || state == OMX_StateExecuting || state == OMX_StatePause))
	{
		fprintf(stderr, "OMX: state is incorrect. State 0x%X; Error 0x%X\n", state, error);
		return;
	}

	// Create audio buffers
	fprintf(stderr, "OMX: creating %u buffers\n", buffer_count);

	// Enable port
	error = OMX_SendCommand(omx_handle, OMX_CommandPortEnable, PORT_INDEX, NULL);
	if(error != OMX_ErrorNone)
		fprintf(stderr, "OMX: failed to do OMX_CommandPortEnable. Error 0x%X\n", error);

	// Free audio buffers if they're allocated
	if(audio_buffers != NULL)
		delete[] audio_buffers;

	// Allocate buffers
	audio_buffers = new OMX_BUFFERHEADERTYPE*[buffer_count];
	for(size_t i = 0; i < buffer_count; i++)
	{
		error = OMX_AllocateBuffer(omx_handle, &audio_buffers[i], PORT_INDEX, NULL, buffer_size);
		if(error != OMX_ErrorNone)
		{
			fprintf(stderr, "OMX: failed to allocate buffer[%u]. Error 0x%X\n", i, error);
			return;
		}
	}

	// Set state to executing
	error = OMX_SendCommand(omx_handle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
	if(error != OMX_ErrorNone)
	{
		fprintf(stderr, "OMX: failed to do OMX_CommandStateSet. Error 0x%X\n", error);
		return;
	}
	omx_wait_for_state(OMX_StateExecuting);

	// Empty buffers
	for(size_t i = 0; i < buffer_count; i++)
	{
		memset(audio_buffers[i]->pBuffer, 0, buffer_size);
		audio_buffers[i]->nOffset = 0;
		audio_buffers[i]->nFilledLen = buffer_size;

		error = OMX_EmptyThisBuffer(omx_handle, audio_buffers[i]);
		if(error != OMX_ErrorNone)
			fprintf(stderr, "OMX: failed to empty buffer[%u]. Error 0x%X\n", i, error);
	}

	char* output_device = "local";
	if(settings.omx.Audio_HDMI)
		output_device = (char*)"hdmi";

	// Set audio destination
	OMX_CONFIG_BRCMAUDIODESTINATIONTYPE ar_dest;
	memset(&ar_dest, 0, sizeof(ar_dest));
	ar_dest.nSize = sizeof(OMX_CONFIG_BRCMAUDIODESTINATIONTYPE);
	ar_dest.nVersion.nVersion = OMX_VERSION;
	strcpy((char *)ar_dest.sName, output_device);
	error = OMX_SetConfig(omx_handle, OMX_IndexConfigBrcmAudioDestination, &ar_dest);
	if(error != OMX_ErrorNone)
	{
		fprintf(stderr, "OMX: failed to set OMX configuration (OMX_IndexConfigBrcmAudioDestination). Error 0x%X\n", error);
		return;
	}

	audio_buffer_idx = 0;
	buffer_length = 0;

	fprintf(stderr, "OMX: audio output to '%s'\n", ar_dest.sName);
}
int
portSettingsChanged(OPENMAX_JPEG_DECODER * decoder)
{
    OMX_PARAM_PORTDEFINITIONTYPE portdef,  rportdef;;
    int ret;

    // CLEANUP

    printf("Pport settings changed\n");
    // need to setup the input for the render with the output of the
    // decoder
    portdef.nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE);
    portdef.nVersion.nVersion = OMX_VERSION;
    portdef.nPortIndex = decoder->imageDecoder->outPort;
    OMX_GetParameter(decoder->imageDecoder->handle,
		     OMX_IndexParamPortDefinition, &portdef);

    // Get default values of render
    rportdef.nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE);
    rportdef.nVersion.nVersion = OMX_VERSION;
    rportdef.nPortIndex = decoder->imageRender->inPort;
    rportdef.nBufferSize = portdef.nBufferSize;

    ret = OMX_GetParameter(decoder->imageRender->handle,
			   OMX_IndexParamPortDefinition, &rportdef);
    if (ret != OMX_ErrorNone) {
	fprintf(stderr, "Error getting render port params %s\n", err2str(ret));
	return OMXJPEG_ERROR_MEMORY;
    }

    // tell render input what the decoder output will be providing
    //Copy some
    rportdef.format.video.nFrameWidth = portdef.format.image.nFrameWidth;
    rportdef.format.video.nFrameHeight = portdef.format.image.nFrameHeight;
    rportdef.format.video.nStride = portdef.format.image.nStride;
    rportdef.format.video.nSliceHeight = portdef.format.image.nSliceHeight;

    ret = OMX_SetParameter(decoder->imageRender->handle,
			   OMX_IndexParamPortDefinition, &rportdef);
    if (ret != OMX_ErrorNone) {
	fprintf(stderr, "Error setting render port params %s\n", err2str(ret));
	return OMXJPEG_ERROR_MEMORY;
    } else {
	printf("Render port params set up ok\n");
    }

    unsigned int    uWidth =
	(unsigned int) portdef.format.image.nFrameWidth;
    unsigned int    uHeight =
	(unsigned int) portdef.format.image.nFrameHeight;
   printf
	("Getting format Compression 0x%x Color Format: 0x%x\n",
	 (unsigned int) portdef.format.image.eCompressionFormat,
	 (unsigned int) portdef.format.image.eColorFormat);
    printColorFormat(portdef.format.image.eColorFormat);

    // enable ports
    OMX_SendCommand(decoder->imageDecoder->handle,
		    OMX_CommandPortEnable,
		    decoder->imageDecoder->outPort, NULL);

    // once the state changes, both ports should become enabled and the
    // render
    // output should generate a settings changed event
    ilclient_wait_for_event(decoder->imageDecoder->component,
			    OMX_EventCmdComplete,
			    OMX_CommandPortEnable, 1,
			    decoder->imageDecoder->outPort, 1, 0,
			    TIMEOUT_MS);
    printf("Decoder output port enabled\n");

    OMX_SendCommand(decoder->imageRender->handle,
		    OMX_CommandPortEnable,
		    decoder->imageRender->inPort, NULL);

    // once the state changes, both ports should become enabled and the
    // render
    // output should generate a settings changed event
    ilclient_wait_for_event(decoder->imageRender->component,
			    OMX_EventCmdComplete,
			    OMX_CommandPortEnable, 1,
			    decoder->imageRender->inPort, 1, 0,
			    TIMEOUT_MS);
    printf("Render input port enabled\n");

    ret = OMX_AllocateBuffer(decoder->imageDecoder->handle,
			     &decoder->pOutputBufferHeader,
			     decoder->imageDecoder->
			     outPort,
			     NULL,
			     portdef.nBufferSize);
    printf("Output port buffer allocated\n");

    if (ret != OMX_ErrorNone) {
	perror("Eror allocating buffer");
	return OMXJPEG_ERROR_MEMORY;
    }

    // and share it with the renderer
    // which has 3 default buffers, 2 minimum
    decoder->ppRenderInputBufferHeader =
	(OMX_BUFFERHEADERTYPE **) malloc(sizeof(void) *
					 decoder->renderInputBufferHeaderCount);
    printState(decoder->imageRender->handle);
			decoder->imageRender->inPort,
    ret = OMX_UseBuffer(decoder->imageRender->handle,
			&decoder->ppRenderInputBufferHeader[0],
			decoder->imageRender->inPort,
			NULL,
			rportdef.nBufferSize,
			decoder->pOutputBufferHeader->pBuffer);
    if (ret != OMX_ErrorNone) {
	fprintf(stderr, "Eror sharing buffer %s\n", err2str(ret));
	return OMXJPEG_ERROR_MEMORY;
    }
    decoder->ppRenderInputBufferHeader[0]->nAllocLen =
	decoder->pOutputBufferHeader->nAllocLen;

    int n;
    for (n = 1; n < decoder->renderInputBufferHeaderCount; n++) {
	printState(decoder->imageRender->handle);
	ret = OMX_UseBuffer(decoder->imageRender->handle,
			    &decoder->ppRenderInputBufferHeader[n],
			    decoder->imageRender->inPort,
			    NULL,
			    0,
			    NULL);
	if (ret != OMX_ErrorNone) {
	    fprintf(stderr, "Eror sharing null buffer %s\n", err2str(ret));
	    return OMXJPEG_ERROR_MEMORY;
	}
    }

    ilclient_wait_for_event(decoder->imageDecoder->component,
			    OMX_EventCmdComplete,
			    OMX_CommandPortEnable, 1,
			    decoder->imageDecoder->outPort, 1, 0,
			    TIMEOUT_MS);
    printf("Decoder output port rnabled\n");

    return OMXJPEG_OK;
}
Пример #24
0
static int init()
{
    OMX_ERRORTYPE err;
    OMX_PARAM_PORTDEFINITIONTYPE paramPort;
    err = OMX_Init();
    printf("om init %d\n", err);
    if (err != OMX_ErrorNone) {
        return 0;
    }
    sem_init(&wait_for_state, 0, 0);
    sem_init(&wait_for_parameters, 0, 0);
    sem_init(&buffer_out_filled, 0, 0);

    err = OMX_GetHandle(&decoderhandle, COMPONENT, NULL, &decodercallbacks);
    OMXE(err);

    // set filepath
    NVX_PARAM_FILENAME filename;
    OMX_INDEXTYPE filename_idx;

    err=OMX_GetExtensionIndex(decoderhandle, FILENAME, &filename_idx);
    OMXE(err);
    printf("filename: %d\n");

    setHeader(&filename, sizeof(filename));

    filename.pFilename = "test.mp4";

    err=OMX_SetParameter(decoderhandle, filename_idx, &filename);
    OMXE(err);

    err = OMX_SendCommand(decoderhandle, OMX_CommandPortDisable, 1, 0);
    OMXE(err);



    setHeader(&paramPort, sizeof(paramPort));
    paramPort.nPortIndex = 0;

    err=OMX_GetParameter(decoderhandle, OMX_IndexParamPortDefinition, &paramPort);
    OMXE(err);


#ifdef DEBUG
    printf("Codec=%d\n", paramPort.format.video.eCompressionFormat);
    printf("Color=%d\n", paramPort.format.video.eColorFormat);
    printf("Size=%dx%d\n", paramPort.format.video.nFrameWidth,
           paramPort.format.video.nFrameHeight);

    printf("Rate=%d\n", paramPort.format.video.xFramerate);

    printf("Requesting %d buffers of %d bytes\n", paramPort.nBufferCountMin, paramPort.nBufferSize);
#endif

    int i;
    for(i=0; i<paramPort.nBufferCountMin; ++i) {
        err = OMX_AllocateBuffer(decoderhandle, &omx_buffers_out[i], 0, NULL, paramPort.nBufferSize);
        OMXE(err);

#ifdef DEBUG
        printf("buf_out[%d]=%p\n", i, omx_buffers_out[i]);
#endif
    }


    buffer_out_nb = paramPort.nBufferCountMin;
    buffer_out_ap = buffer_out_nb;
    buffer_out_avp = 0;

    buffer_out_pos=0;
    buffer_out_size=paramPort.nBufferSize;

    printf("idle\n");
    GoToState(OMX_StateIdle);

    printf("go executing\n");
    GoToState(OMX_StateExecuting);


    return 1;
}
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;
    }
Пример #26
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;
}
int
startupImageDecoder(OPENMAX_JPEG_DECODER * decoder)
{
    // move to idle
    ilclient_change_component_state(decoder->imageDecoder->component,
				    OMX_StateIdle);

    // set input image format
    OMX_IMAGE_PARAM_PORTFORMATTYPE imagePortFormat;
    memset(&imagePortFormat, 0, sizeof(OMX_IMAGE_PARAM_PORTFORMATTYPE));
    imagePortFormat.nSize = sizeof(OMX_IMAGE_PARAM_PORTFORMATTYPE);
    imagePortFormat.nVersion.nVersion = OMX_VERSION;
    imagePortFormat.nPortIndex = decoder->imageDecoder->inPort;
    imagePortFormat.eCompressionFormat = OMX_IMAGE_CodingJPEG;
    OMX_SetParameter(decoder->imageDecoder->handle,
		     OMX_IndexParamImagePortFormat, &imagePortFormat);

    // get buffer requirements
    OMX_PARAM_PORTDEFINITIONTYPE portdef;
    portdef.nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE);
    portdef.nVersion.nVersion = OMX_VERSION;
    portdef.nPortIndex = decoder->imageDecoder->inPort;
    OMX_GetParameter(decoder->imageDecoder->handle,
		     OMX_IndexParamPortDefinition, &portdef);

    // enable the port and setup the buffers
    OMX_SendCommand(decoder->imageDecoder->handle,
		    OMX_CommandPortEnable,
		    decoder->imageDecoder->inPort, NULL);
    decoder->inputBufferHeaderCount = portdef.nBufferCountActual;
    // allocate pointer array
    decoder->ppInputBufferHeader =
	(OMX_BUFFERHEADERTYPE **) malloc(sizeof(void) *
					 decoder->inputBufferHeaderCount);
    // allocate each buffer
    int             i;
    for (i = 0; i < decoder->inputBufferHeaderCount; i++) {
	if (OMX_AllocateBuffer(decoder->imageDecoder->handle,
			       &decoder->ppInputBufferHeader[i],
			       decoder->imageDecoder->inPort,
			       (void *) i,
			       portdef.nBufferSize) != OMX_ErrorNone) {
	    perror("Allocate decode buffer");
	    return OMXJPEG_ERROR_MEMORY;
	}
    }
    // wait for port enable to complete - which it should once buffers are 
    // assigned
    int             ret =
	ilclient_wait_for_event(decoder->imageDecoder->component,
				OMX_EventCmdComplete,
				OMX_CommandPortEnable, 0,
				decoder->imageDecoder->inPort, 0,
				0, TIMEOUT_MS);
    if (ret != 0) {
	fprintf(stderr, "Did not get port enable %d\n", ret);
	return OMXJPEG_ERROR_EXECUTING;
    } else {
	printf("Ddecoder input port enabled after buffers allocated\n");
    }

    ret = ilclient_wait_for_event(decoder->imageDecoder->component,
				  OMX_EventCmdComplete,
				  OMX_StateIdle, 0, 0, 1, 0,
				  TIMEOUT_MS);
    if (ret != 0) {
	fprintf(stderr, "Did not receive executing stat %d\n", ret);
	// return OMXJPEG_ERROR_EXECUTING;
    } else {
	printf("Decoder now in idle state\n");
    }

    // start executing the decoder 
    ret = OMX_SendCommand(decoder->imageDecoder->handle,
			  OMX_CommandStateSet, OMX_StateExecuting, NULL);
    if (ret != 0) {
	fprintf(stderr, "Error starting image decoder %x\n", ret);
	return OMXJPEG_ERROR_EXECUTING;
    }
    ret = ilclient_wait_for_event(decoder->imageDecoder->component,
				  OMX_EventCmdComplete,
				  OMX_StateExecuting, 0, 0, 1, 0,
				  TIMEOUT_MS);
    if (ret != 0) {
	fprintf(stderr, "Did not receive executing stat %d\n", ret);
	// return OMXJPEG_ERROR_EXECUTING;
    }

    return OMXJPEG_OK;
}
void OmxDecTestWithoutMarker::Run()
{
    switch (iState)
    {
    case StateUnLoaded:
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateUnLoaded IN"));
        OMX_ERRORTYPE Err;
        OMX_BOOL Status;

        if (!iCallbacks->initCallbacks())
        {
            PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR, (0, "OmxDecTestWithoutMarker::Run() - ERROR initCallbacks failed, OUT"));
            StopOnError();
            break;
        }

        ipAppPriv = (AppPrivateType*) oscl_malloc(sizeof(AppPrivateType));
        CHECK_MEM(ipAppPriv, "Component_Handle");
        ipAppPriv->Handle = NULL;

        //Allocate bitstream buffer for AVC component
        if (0 == oscl_strcmp(iFormat, "H264"))
        {
            ipAVCBSO = OSCL_NEW(AVCBitstreamObject, (ipInputFile));
            CHECK_MEM(ipAVCBSO, "Bitstream_Buffer");
        }

        //Allocate bitstream buffer for MPEG4/H263 component
        if (0 == oscl_strcmp(iFormat, "M4V") || 0 == oscl_strcmp(iFormat, "H263"))
        {
            ipBitstreamBuffer = (OMX_U8*) oscl_malloc(BIT_BUFF_SIZE);
            CHECK_MEM(ipBitstreamBuffer, "Bitstream_Buffer")
            ipBitstreamBufferPointer = ipBitstreamBuffer;
        }

        iNoMarkerBitTest = OMX_TRUE;

        //This should be the first call to the component to load it.
        Err = OMX_MasterInit();
        CHECK_ERROR(Err, "OMX_MasterInit");
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG, (0, "OmxDecTestWithoutMarker::Run() - OMX_MasterInit done"));


        Status = PrepareComponent();

        if (OMX_FALSE == Status)
        {
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG, (0, "OmxDecTestWithoutMarker::Run() Error while loading component OUT"));
            iState = StateError;

            if (iInputParameters.inPtr)
            {
                oscl_free(iInputParameters.inPtr);
                iInputParameters.inPtr = NULL;
            }

            RunIfNotReady();
            break;
        }


#if PROXY_INTERFACE
        ipThreadSafeHandlerEventHandler = OSCL_NEW(OmxEventHandlerThreadSafeCallbackAO, (this, EVENT_HANDLER_QUEUE_DEPTH, "EventHandlerAO"));
        ipThreadSafeHandlerEmptyBufferDone = OSCL_NEW(OmxEmptyBufferDoneThreadSafeCallbackAO, (this, iInBufferCount, "EmptyBufferDoneAO"));
        ipThreadSafeHandlerFillBufferDone = OSCL_NEW(OmxFillBufferDoneThreadSafeCallbackAO, (this, iOutBufferCount, "FillBufferDoneAO"));

        if ((NULL == ipThreadSafeHandlerEventHandler) ||
                (NULL == ipThreadSafeHandlerEmptyBufferDone) ||
                (NULL == ipThreadSafeHandlerFillBufferDone))
        {
            PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR,
                            (0, "OmxDecTestWithoutMarker::Run() - Error ThreadSafe Callback Handler initialization failed, OUT"));

            iState = StateUnLoaded;
            OsclExecScheduler* sched = OsclExecScheduler::Current();
            sched->StopScheduler();
        }
#endif

        if (StateError != iState)
        {
            iState = StateLoaded;
            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateUnLoaded OUT, moving to next state"));
        }

        RunIfNotReady();
    }
    break;

    case StateLoaded:
    {
        OMX_ERRORTYPE Err;
        OMX_U32 ii;

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateLoaded IN"));

        // allocate memory for ipInBuffer
        ipInBuffer = (OMX_BUFFERHEADERTYPE**) oscl_malloc(sizeof(OMX_BUFFERHEADERTYPE*) * iInBufferCount);
        CHECK_MEM(ipInBuffer, "InputBufferHeader");

        ipInputAvail = (OMX_BOOL*) oscl_malloc(sizeof(OMX_BOOL) * iInBufferCount);
        CHECK_MEM(ipInputAvail, "InputBufferFlag");

        /* Initialize all the buffers to NULL */
        for (ii = 0; ii < iInBufferCount; ii++)
        {
            ipInBuffer[ii] = NULL;
        }

        //allocate memory for output buffer
        ipOutBuffer = (OMX_BUFFERHEADERTYPE**) oscl_malloc(sizeof(OMX_BUFFERHEADERTYPE*) * iOutBufferCount);
        CHECK_MEM(ipOutBuffer, "OutputBuffer");

        ipOutReleased = (OMX_BOOL*) oscl_malloc(sizeof(OMX_BOOL) * iOutBufferCount);
        CHECK_MEM(ipOutReleased, "OutputBufferFlag");

        /* Initialize all the buffers to NULL */
        for (ii = 0; ii < iOutBufferCount; ii++)
        {
            ipOutBuffer[ii] = NULL;
        }

        Err = OMX_SendCommand(ipAppPriv->Handle, OMX_CommandStateSet, OMX_StateIdle, NULL);
        CHECK_ERROR(Err, "SendCommand Loaded->Idle");

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                        (0, "OmxDecTestWithoutMarker::Run() - Sent State Transition Command from Loaded->Idle"));

        iPendingCommands = 1;

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                        (0, "OmxDecTestWithoutMarker::Run() - Allocating %d input and %d output buffers", iInBufferCount, iOutBufferCount));

        //These calls are required because the control of in & out buffer should be with the testapp.
        for (ii = 0; ii < iInBufferCount; ii++)
        {
            Err = OMX_AllocateBuffer(ipAppPriv->Handle, &ipInBuffer[ii], iInputPortIndex, NULL, iInBufferSize);
            CHECK_ERROR(Err, "AllocateBuffer_Input");

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                            (0, "OmxDecTestWithoutMarker::Run() - Called AllocateBuffer for buffer index %d on port %d", ii, iInputPortIndex));

            ipInputAvail[ii] = OMX_TRUE;
            ipInBuffer[ii]->nInputPortIndex = iInputPortIndex;
        }

        if (StateError == iState)
        {
            PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR,
                            (0, "OmxDecTestWithoutMarker::Run() - AllocateBuffer Error, StateLoaded OUT"));
            RunIfNotReady();
            break;
        }

        for (ii = 0; ii < iOutBufferCount; ii++)
        {
            Err = OMX_AllocateBuffer(ipAppPriv->Handle, &ipOutBuffer[ii], iOutputPortIndex, NULL, iOutBufferSize);
            CHECK_ERROR(Err, "AllocateBuffer_Output");

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                            (0, "OmxDecTestWithoutMarker::Run() - Called AllocateBuffer for buffer index %d on port %d", ii, iOutputPortIndex));

            ipOutReleased[ii] = OMX_TRUE;

            ipOutBuffer[ii]->nOutputPortIndex = iOutputPortIndex;
            ipOutBuffer[ii]->nInputPortIndex = 0;
        }
        if (StateError == iState)
        {
            PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR,
                            (0, "OmxDecTestWithoutMarker::Run() - AllocateBuffer Error, StateLoaded OUT"));
            RunIfNotReady();
            break;
        }

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateLoaded OUT, Moving to next state"));

    }
    break;

    case StateIdle:
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateIdle IN"));

        OMX_ERRORTYPE Err = OMX_ErrorNone;

        /*Send an output buffer before dynamic reconfig */
        Err = OMX_FillThisBuffer(ipAppPriv->Handle, ipOutBuffer[0]);
        CHECK_ERROR(Err, "FillThisBuffer");

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                        (0, "OmxDecTestWithoutMarker::Run() - FillThisBuffer command called for initiating dynamic port reconfiguration"));

        ipOutReleased[0] = OMX_FALSE;

        Err = OMX_SendCommand(ipAppPriv->Handle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
        CHECK_ERROR(Err, "SendCommand Idle->Executing");

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                        (0, "OmxDecTestWithoutMarker::Run() - Sent State Transition Command from Idle->Executing"));

        iPendingCommands = 1;

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateIdle OUT"));
    }
    break;

    case StateDecodeHeader:
    {
        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE,
                        (0, "OmxDecTestWithoutMarker::Run() - StateDecodeHeader IN, Sending configuration input buffers to the component to start dynamic port reconfiguration"));

        if (!iFlagDecodeHeader)
        {
            if (0 == oscl_strcmp(iFormat, "WMV") || 0 == oscl_strcmp(iFormat, "WMA") || 0 == oscl_strcmp(iFormat, "RV") || 0 == oscl_strcmp(iFormat, "RA"))
            {
                (*this.*pGetInputFrame)();
            }
            else
            {
                GetInput();
            }
            iFlagDecodeHeader = OMX_TRUE;

            //Proceed to executing state and if Port settings changed callback comes,
            //then do the dynamic port reconfiguration
            iState = StateExecuting;

            RunIfNotReady();
        }

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateDecodeHeader OUT"));
    }
    break;

    case StateDisablePort:
    {
        OMX_ERRORTYPE Err = OMX_ErrorNone;
        OMX_U32 ii;

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateDisablePort IN"));

        if (!iDisableRun)
        {
            if (!iFlagDisablePort)
            {
                Err = OMX_SendCommand(ipAppPriv->Handle, OMX_CommandPortDisable, iOutputPortIndex, NULL);
                CHECK_ERROR(Err, "SendCommand_PortDisable");

                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                (0, "OmxDecTestWithoutMarker::Run() - Sent Command for OMX_CommandPortDisable on port %d as a part of dynamic port reconfiguration", iOutputPortIndex));

                iPendingCommands = 1;
                iFlagDisablePort = OMX_TRUE;
                RunIfNotReady();
            }
            else
            {
                //Wait for all the buffers to be returned on output port before freeing them
                //This wait is required because of the queueing delay in all the Callbacks
                for (ii = 0; ii < iOutBufferCount; ii++)
                {
                    if (OMX_FALSE == ipOutReleased[ii])
                    {
                        break;
                    }
                }

                if (ii != iOutBufferCount)
                {
                    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                    (0, "OmxDecTestWithoutMarker::Run() - Not all the output buffers returned by component yet, wait for it"));
                    RunIfNotReady();
                    break;
                }

                for (ii = 0; ii < iOutBufferCount; ii++)
                {
                    if (ipOutBuffer[ii])
                    {
                        Err = OMX_FreeBuffer(ipAppPriv->Handle, iOutputPortIndex, ipOutBuffer[ii]);
                        CHECK_ERROR(Err, "FreeBuffer_Output_DynamicReconfig");
                        ipOutBuffer[ii] = NULL;

                        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                        (0, "OmxDecTestWithoutMarker::Run() - Called FreeBuffer for buffer index %d on port %d", ii, iOutputPortIndex));
                    }
                }

                if (ipOutBuffer)
                {
                    oscl_free(ipOutBuffer);
                    ipOutBuffer = NULL;
                }

                if (ipOutReleased)
                {
                    oscl_free(ipOutReleased);
                    ipOutReleased = NULL;
                }

                if (StateError == iState)
                {
                    PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR,
                                    (0, "OmxDecTestWithoutMarker::Run() - Error occured in this state, StateDisablePort OUT"));
                    RunIfNotReady();
                    break;
                }
                iDisableRun = OMX_TRUE;
            }
        }

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateDisablePort OUT"));
    }
    break;

    case StateDynamicReconfig:
    {
        OMX_BOOL Status = OMX_TRUE;

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateDynamicReconfig IN"));

        Status = HandlePortReEnable();
        if (OMX_FALSE == Status)
        {
            PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR,
                            (0, "OmxDecTestWithoutMarker::Run() - Error occured in this state, StateDynamicReconfig OUT"));
            iState = StateError;
            RunIfNotReady();
            break;
        }

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateDynamicReconfig OUT"));
    }
    break;

    case StateExecuting:
    {
        OMX_U32 Index;
        OMX_BOOL MoreOutput;
        OMX_ERRORTYPE Err = OMX_ErrorNone;

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateExecuting IN"));

        MoreOutput = OMX_TRUE;
        while (MoreOutput)
        {
            Index = 0;
            while (OMX_FALSE == ipOutReleased[Index] && Index < iOutBufferCount)
            {
                Index++;
            }

            if (Index != iOutBufferCount)
            {
                //This call is being made only once per frame
                Err = OMX_FillThisBuffer(ipAppPriv->Handle, ipOutBuffer[Index]);
                CHECK_ERROR(Err, "FillThisBuffer");
                //Make this flag OMX_TRUE till u receive the callback for output buffer free
                ipOutReleased[Index] = OMX_FALSE;

                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                (0, "OmxDecTestWithoutMarker::Run() - FillThisBuffer command called for output buffer index %d", Index));
            }
            else
            {
                MoreOutput = OMX_FALSE;
            }
        }


        if (!iStopProcessingInput || (OMX_ErrorInsufficientResources == iStatusExecuting))
        {
            if (0 == oscl_strcmp(iFormat, "WMV") || 0 == oscl_strcmp(iFormat, "WMA") || 0 == oscl_strcmp(iFormat, "RV") || 0 == oscl_strcmp(iFormat, "RA"))
            {
                iStatusExecuting = (*this.*pGetInputFrame)();
            }
            else
            {
                iStatusExecuting = GetInput();
            }
        }
        else if (OMX_FALSE == iEosFlagExecuting)
        {
            //Only send one successful dummy buffer with flag set to signal EOS
            Index = 0;
            while (OMX_FALSE == ipInputAvail[Index] && Index < iInBufferCount)
            {
                Index++;
            }

            if (Index != iInBufferCount)
            {
                ipInBuffer[Index]->nFlags |= OMX_BUFFERFLAG_EOS;
                ipInBuffer[Index]->nFilledLen = 0;
                Err = OMX_EmptyThisBuffer(ipAppPriv->Handle, ipInBuffer[Index]);

                CHECK_ERROR(Err, "EmptyThisBuffer_EOS");

                ipInputAvail[Index] = OMX_FALSE; // mark unavailable
                iEosFlagExecuting = OMX_TRUE;

                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                (0, "OmxDecTestWithoutMarker::Run() - Input buffer sent to the component with OMX_BUFFERFLAG_EOS flag set"));
            }
        }
        else
        {
            //nothing to do here
        }

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateExecuting OUT"));
        RunIfNotReady();
    }
    break;

    case StateStopping:
    {
        OMX_ERRORTYPE Err = OMX_ErrorNone;

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateStopping IN"));

        //stop execution by state transition to Idle state.
        if (!iFlagStopping)
        {
            Err = OMX_SendCommand(ipAppPriv->Handle, OMX_CommandStateSet, OMX_StateIdle, NULL);
            CHECK_ERROR(Err, "SendCommand Executing->Idle");

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                            (0, "OmxDecTestWithoutMarker::Run() - Sent State Transition Command from Executing->Idle"));

            iPendingCommands = 1;
            iFlagStopping = OMX_TRUE;
        }

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateStopping OUT"));
    }
    break;

    case StateCleanUp:
    {
        OMX_U32 ii;
        OMX_ERRORTYPE Err = OMX_ErrorNone;

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateCleanUp IN"));

        if (!iFlagCleanUp)
        {
            //Added a check here to verify whether all the ip/op buffers are returned back by the component or not
            //in case of Executing->Idle state transition

            if (OMX_FALSE == VerifyAllBuffersReturned())
            {
                // not all buffers have been returned yet, reschedule
                RunIfNotReady();
                break;
            }

            //Destroy the component by state transition to Loaded state
            Err = OMX_SendCommand(ipAppPriv->Handle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
            CHECK_ERROR(Err, "SendCommand Idle->Loaded");

            PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                            (0, "OmxDecTestWithoutMarker::Run() - Sent State Transition Command from Idle->Loaded"));

            iPendingCommands = 1;

            if (ipInBuffer)
            {
                for (ii = 0; ii < iInBufferCount; ii++)
                {
                    if (ipInBuffer[ii])
                    {
                        Err = OMX_FreeBuffer(ipAppPriv->Handle, iInputPortIndex, ipInBuffer[ii]);
                        CHECK_ERROR(Err, "FreeBuffer_Input");
                        ipInBuffer[ii] = NULL;

                        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                        (0, "OmxDecTestWithoutMarker::Run() - Called FreeBuffer for buffer index %d on port %d", ii, iInputPortIndex));
                    }
                }

                oscl_free(ipInBuffer);
                ipInBuffer = NULL;
            }

            if (ipInputAvail)
            {
                oscl_free(ipInputAvail);
                ipInputAvail = NULL;
            }


            if (ipOutBuffer)
            {
                for (ii = 0; ii < iOutBufferCount; ii++)
                {
                    if (ipOutBuffer[ii])
                    {
                        Err = OMX_FreeBuffer(ipAppPriv->Handle, iOutputPortIndex, ipOutBuffer[ii]);
                        CHECK_ERROR(Err, "FreeBuffer_Output");
                        ipOutBuffer[ii] = NULL;

                        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                        (0, "OmxDecTestWithoutMarker::Run() - Called FreeBuffer for buffer index %d on port %d", ii, iOutputPortIndex));
                    }
                }
                oscl_free(ipOutBuffer);
                ipOutBuffer = NULL;
            }

            if (ipOutReleased)
            {
                oscl_free(ipOutReleased);
                ipOutReleased = NULL;
            }
            iFlagCleanUp = OMX_TRUE;
        }

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateCleanUp OUT"));

    }
    break;


    /********* FREE THE HANDLE & CLOSE FILES FOR THE COMPONENT ********/
    case StateStop:
    {
        OMX_U8 TestName[] = "WITHOUT_MARKER_BIT_TEST";
        OMX_ERRORTYPE Err = OMX_ErrorNone;

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateStop IN"));

        if (ipAppPriv)
        {
            if (ipAppPriv->Handle)
            {
                PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                (0, "OmxDecTestWithoutMarker::Run() - Free the Component Handle"));

                Err = OMX_MasterFreeHandle(ipAppPriv->Handle);
                if (OMX_ErrorNone != Err)
                {
                    PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR, (0, "OmxDecTestWithoutMarker::Run() - FreeHandle Error"));
                    iTestStatus = OMX_FALSE;
                }
            }
        }

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                        (0, "OmxDecTestWithoutMarker::Run() - De-initialize the omx component"));

        Err = OMX_MasterDeinit();
        if (OMX_ErrorNone != Err)
        {
            PVLOGGER_LOGMSG(PVLOGMSG_INST_HLDBG, iLogger, PVLOGMSG_ERR, (0, "OmxDecTestWithoutMarker::Run() - OMX_MasterDeinit Error"));
            iTestStatus = OMX_FALSE;
        }

        if (0 == oscl_strcmp(iFormat, "H264"))
        {
            if (ipAVCBSO)
            {
                OSCL_DELETE(ipAVCBSO);
                ipAVCBSO = NULL;
            }
        }

        if (0 == oscl_strcmp(iFormat, "M4V") || 0 == oscl_strcmp(iFormat, "H263"))
        {
            if (ipBitstreamBuffer)
            {
                oscl_free(ipBitstreamBufferPointer);
                ipBitstreamBuffer = NULL;
                ipBitstreamBufferPointer = NULL;
            }
        }

        if (iOutputParameters)
        {
            oscl_free(iOutputParameters);
            iOutputParameters = NULL;
        }

        if (ipAppPriv)
        {
            oscl_free(ipAppPriv);
            ipAppPriv = NULL;
        }

#if PROXY_INTERFACE
        if (ipThreadSafeHandlerEventHandler)
        {
            OSCL_DELETE(ipThreadSafeHandlerEventHandler);
            ipThreadSafeHandlerEventHandler = NULL;
        }

        if (ipThreadSafeHandlerEmptyBufferDone)
        {
            OSCL_DELETE(ipThreadSafeHandlerEmptyBufferDone);
            ipThreadSafeHandlerEmptyBufferDone = NULL;
        }

        if (ipThreadSafeHandlerFillBufferDone)
        {
            OSCL_DELETE(ipThreadSafeHandlerFillBufferDone);
            ipThreadSafeHandlerFillBufferDone = NULL;
        }
#endif

        VerifyOutput(TestName);

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateStop OUT"));

        iState = StateUnLoaded;
        OsclExecScheduler* sched = OsclExecScheduler::Current();
        sched->StopScheduler();
    }
    break;

    case StateError:
    {
        //Do all the cleanup's and exit from here
        OMX_U32 ii;

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateError IN"));

        iTestStatus = OMX_FALSE;

        if (ipInBuffer)
        {
            for (ii = 0; ii < iInBufferCount; ii++)
            {
                if (ipInBuffer[ii])
                {
                    OMX_FreeBuffer(ipAppPriv->Handle, iInputPortIndex, ipInBuffer[ii]);
                    ipInBuffer[ii] = NULL;

                    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                    (0, "OmxDecTestWithoutMarker::Run() - Called FreeBuffer for buffer index %d on port %d", ii, iInputPortIndex));
                }
            }
            oscl_free(ipInBuffer);
            ipInBuffer =  NULL;
        }

        if (ipInputAvail)
        {
            oscl_free(ipInputAvail);
            ipInputAvail = NULL;
        }

        if (ipOutBuffer)
        {
            for (ii = 0; ii < iOutBufferCount; ii++)
            {
                if (ipOutBuffer[ii])
                {
                    OMX_FreeBuffer(ipAppPriv->Handle, iOutputPortIndex, ipOutBuffer[ii]);
                    ipOutBuffer[ii] = NULL;

                    PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_DEBUG,
                                    (0, "OmxDecTestWithoutMarker::Run() - Called FreeBuffer for buffer index %d on port %d", ii, iOutputPortIndex));
                }
            }
            oscl_free(ipOutBuffer);
            ipOutBuffer = NULL;
        }

        if (ipOutReleased)
        {
            oscl_free(ipOutReleased);
            ipOutReleased = NULL;
        }

        iState = StateStop;
        RunIfNotReady();

        PVLOGGER_LOGMSG(PVLOGMSG_INST_LLDBG, iLogger, PVLOGMSG_STACK_TRACE, (0, "OmxDecTestWithoutMarker::Run() - StateError OUT"));

    }
    break;

    default:
    {
        break;
    }
    }
    return ;
}
Пример #29
0
OMX_ERRORTYPE COMXCoreComponent::AllocOutputBuffers(bool use_buffers /* = false */)
{
  OMX_ERRORTYPE omx_err = OMX_ErrorNone;

  if(!m_handle)
    return OMX_ErrorUndefined;

  m_omx_output_use_buffers = use_buffers; 

  OMX_PARAM_PORTDEFINITIONTYPE portFormat;
  OMX_INIT_STRUCTURE(portFormat);
  portFormat.nPortIndex = m_output_port;

  omx_err = OMX_GetParameter(m_handle, OMX_IndexParamPortDefinition, &portFormat);
  if(omx_err != OMX_ErrorNone)
    return omx_err;

  if(GetState() != OMX_StateIdle)
  {
    if(GetState() != OMX_StateLoaded)
      SetStateForComponent(OMX_StateLoaded);

    SetStateForComponent(OMX_StateIdle);
  }

  omx_err = EnablePort(m_output_port, false);
  if(omx_err != OMX_ErrorNone)
    return omx_err;

  m_output_alignment     = portFormat.nBufferAlignment;
  m_output_buffer_count  = portFormat.nBufferCountActual;
  m_output_buffer_size   = portFormat.nBufferSize;

  CLog::Log(LOGDEBUG, "COMXCoreComponent::AllocOutputBuffers component(%s) - port(%d), nBufferCountMin(%lu), nBufferCountActual(%lu), nBufferSize(%lu) nBufferAlignmen(%lu)\n",
            m_componentName.c_str(), m_output_port, portFormat.nBufferCountMin,
            portFormat.nBufferCountActual, portFormat.nBufferSize, portFormat.nBufferAlignment);

  for (size_t i = 0; i < portFormat.nBufferCountActual; i++)
  {
    OMX_BUFFERHEADERTYPE *buffer = NULL;
    OMX_U8* data = NULL;

    if(m_omx_output_use_buffers)
    {
      data = (OMX_U8*)_aligned_malloc(portFormat.nBufferSize, m_output_alignment);
      omx_err = OMX_UseBuffer(m_handle, &buffer, m_output_port, NULL, portFormat.nBufferSize, data);
    }
    else
    {
      omx_err = OMX_AllocateBuffer(m_handle, &buffer, m_output_port, NULL, portFormat.nBufferSize);
    }
    if(omx_err != OMX_ErrorNone)
    {
      CLog::Log(LOGERROR, "COMXCoreComponent::AllocOutputBuffers component(%s) - OMX_UseBuffer failed with omx_err(0x%x)\n",
        m_componentName.c_str(), omx_err);

      if(m_omx_output_use_buffers && data)
       _aligned_free(data);

      return omx_err;
    }
    buffer->nOutputPortIndex = m_output_port;
    buffer->nFilledLen       = 0;
    buffer->nOffset          = 0;
    buffer->pAppPrivate      = (void*)i;
    m_omx_output_buffers.push_back(buffer);
    m_omx_output_available.push(buffer);
  }

  omx_err = WaitForCommand(OMX_CommandPortEnable, m_output_port);

  m_flush_output = false;

  return omx_err;
}
Пример #30
0
static av_cold int omx_component_init(AVCodecContext *avctx, const char *role)
{
    OMXCodecContext *s = avctx->priv_data;
    OMX_PARAM_COMPONENTROLETYPE role_params = { 0 };
    OMX_PORT_PARAM_TYPE video_port_params = { 0 };
    OMX_PARAM_PORTDEFINITIONTYPE in_port_params = { 0 }, out_port_params = { 0 };
    OMX_VIDEO_PARAM_PORTFORMATTYPE video_port_format = { 0 };
    OMX_VIDEO_PARAM_BITRATETYPE vid_param_bitrate = { 0 };
    OMX_ERRORTYPE err;
    int i;

    s->version.s.nVersionMajor = 1;
    s->version.s.nVersionMinor = 1;
    s->version.s.nRevision     = 2;

    err = s->omx_context->ptr_GetHandle(&s->handle, s->component_name, s, (OMX_CALLBACKTYPE*) &callbacks);
    if (err != OMX_ErrorNone) {
        av_log(avctx, AV_LOG_ERROR, "OMX_GetHandle(%s) failed: %x\n", s->component_name, err);
        return AVERROR_UNKNOWN;
    }

    // This one crashes the mediaserver on qcom, if used over IOMX
    INIT_STRUCT(role_params);
    av_strlcpy(role_params.cRole, role, sizeof(role_params.cRole));
    // Intentionally ignore errors on this one
    OMX_SetParameter(s->handle, OMX_IndexParamStandardComponentRole, &role_params);

    INIT_STRUCT(video_port_params);
    err = OMX_GetParameter(s->handle, OMX_IndexParamVideoInit, &video_port_params);
    CHECK(err);

    s->in_port = s->out_port = -1;
    for (i = 0; i < video_port_params.nPorts; i++) {
        int port = video_port_params.nStartPortNumber + i;
        OMX_PARAM_PORTDEFINITIONTYPE port_params = { 0 };
        INIT_STRUCT(port_params);
        port_params.nPortIndex = port;
        err = OMX_GetParameter(s->handle, OMX_IndexParamPortDefinition, &port_params);
        if (err != OMX_ErrorNone) {
            av_log(avctx, AV_LOG_WARNING, "port %d error %x\n", port, err);
            break;
        }
        if (port_params.eDir == OMX_DirInput && s->in_port < 0) {
            in_port_params = port_params;
            s->in_port = port;
        } else if (port_params.eDir == OMX_DirOutput && s->out_port < 0) {
            out_port_params = port_params;
            s->out_port = port;
        }
    }
    if (s->in_port < 0 || s->out_port < 0) {
        av_log(avctx, AV_LOG_ERROR, "No in or out port found (in %d out %d)\n", s->in_port, s->out_port);
        return AVERROR_UNKNOWN;
    }

    s->color_format = 0;
    for (i = 0; ; i++) {
        INIT_STRUCT(video_port_format);
        video_port_format.nIndex = i;
        video_port_format.nPortIndex = s->in_port;
        if (OMX_GetParameter(s->handle, OMX_IndexParamVideoPortFormat, &video_port_format) != OMX_ErrorNone)
            break;
        if (video_port_format.eColorFormat == OMX_COLOR_FormatYUV420Planar ||
            video_port_format.eColorFormat == OMX_COLOR_FormatYUV420PackedPlanar) {
            s->color_format = video_port_format.eColorFormat;
            break;
        }
    }
    if (s->color_format == 0) {
        av_log(avctx, AV_LOG_ERROR, "No supported pixel formats (%d formats available)\n", i);
        return AVERROR_UNKNOWN;
    }

    in_port_params.bEnabled   = OMX_TRUE;
    in_port_params.bPopulated = OMX_FALSE;
    in_port_params.eDomain    = OMX_PortDomainVideo;

    in_port_params.format.video.pNativeRender         = NULL;
    in_port_params.format.video.bFlagErrorConcealment = OMX_FALSE;
    in_port_params.format.video.eColorFormat          = s->color_format;
    s->stride     = avctx->width;
    s->plane_size = avctx->height;
    // If specific codecs need to manually override the stride/plane_size,
    // that can be done here.
    in_port_params.format.video.nStride      = s->stride;
    in_port_params.format.video.nSliceHeight = s->plane_size;
    in_port_params.format.video.nFrameWidth  = avctx->width;
    in_port_params.format.video.nFrameHeight = avctx->height;
    if (avctx->framerate.den > 0 && avctx->framerate.num > 0)
        in_port_params.format.video.xFramerate = (1 << 16) * avctx->framerate.num / avctx->framerate.den;
    else
        in_port_params.format.video.xFramerate = (1 << 16) * avctx->time_base.den / avctx->time_base.num;

    err = OMX_SetParameter(s->handle, OMX_IndexParamPortDefinition, &in_port_params);
    CHECK(err);
    err = OMX_GetParameter(s->handle, OMX_IndexParamPortDefinition, &in_port_params);
    CHECK(err);
    s->stride         = in_port_params.format.video.nStride;
    s->plane_size     = in_port_params.format.video.nSliceHeight;
    s->num_in_buffers = in_port_params.nBufferCountActual;

    err = OMX_GetParameter(s->handle, OMX_IndexParamPortDefinition, &out_port_params);
    out_port_params.bEnabled   = OMX_TRUE;
    out_port_params.bPopulated = OMX_FALSE;
    out_port_params.eDomain    = OMX_PortDomainVideo;
    out_port_params.format.video.pNativeRender = NULL;
    out_port_params.format.video.nFrameWidth   = avctx->width;
    out_port_params.format.video.nFrameHeight  = avctx->height;
    out_port_params.format.video.nStride       = 0;
    out_port_params.format.video.nSliceHeight  = 0;
    out_port_params.format.video.nBitrate      = avctx->bit_rate;
    out_port_params.format.video.xFramerate    = in_port_params.format.video.xFramerate;
    out_port_params.format.video.bFlagErrorConcealment  = OMX_FALSE;
    if (avctx->codec->id == AV_CODEC_ID_MPEG4)
        out_port_params.format.video.eCompressionFormat = OMX_VIDEO_CodingMPEG4;
    else if (avctx->codec->id == AV_CODEC_ID_H264)
        out_port_params.format.video.eCompressionFormat = OMX_VIDEO_CodingAVC;

    err = OMX_SetParameter(s->handle, OMX_IndexParamPortDefinition, &out_port_params);
    CHECK(err);
    err = OMX_GetParameter(s->handle, OMX_IndexParamPortDefinition, &out_port_params);
    CHECK(err);
    s->num_out_buffers = out_port_params.nBufferCountActual;

    INIT_STRUCT(vid_param_bitrate);
    vid_param_bitrate.nPortIndex     = s->out_port;
    vid_param_bitrate.eControlRate   = OMX_Video_ControlRateVariable;
    vid_param_bitrate.nTargetBitrate = avctx->bit_rate;
    err = OMX_SetParameter(s->handle, OMX_IndexParamVideoBitrate, &vid_param_bitrate);
    if (err != OMX_ErrorNone)
        av_log(avctx, AV_LOG_WARNING, "Unable to set video bitrate parameter\n");

    if (avctx->codec->id == AV_CODEC_ID_H264) {
        OMX_VIDEO_PARAM_AVCTYPE avc = { 0 };
        INIT_STRUCT(avc);
        avc.nPortIndex = s->out_port;
        err = OMX_GetParameter(s->handle, OMX_IndexParamVideoAvc, &avc);
        CHECK(err);
        avc.nBFrames = 0;
        avc.nPFrames = avctx->gop_size - 1;
        switch (s->profile == FF_PROFILE_UNKNOWN ? avctx->profile : s->profile) {
        case FF_PROFILE_H264_BASELINE:
            avc.eProfile = OMX_VIDEO_AVCProfileBaseline;
            break;
        case FF_PROFILE_H264_MAIN:
            avc.eProfile = OMX_VIDEO_AVCProfileMain;
            break;
        case FF_PROFILE_H264_HIGH:
            avc.eProfile = OMX_VIDEO_AVCProfileHigh;
            break;
        default:
            break;
        }
        err = OMX_SetParameter(s->handle, OMX_IndexParamVideoAvc, &avc);
        CHECK(err);
    }

    err = OMX_SendCommand(s->handle, OMX_CommandStateSet, OMX_StateIdle, NULL);
    CHECK(err);

    s->in_buffer_headers  = av_mallocz(sizeof(OMX_BUFFERHEADERTYPE*) * s->num_in_buffers);
    s->free_in_buffers    = av_mallocz(sizeof(OMX_BUFFERHEADERTYPE*) * s->num_in_buffers);
    s->out_buffer_headers = av_mallocz(sizeof(OMX_BUFFERHEADERTYPE*) * s->num_out_buffers);
    s->done_out_buffers   = av_mallocz(sizeof(OMX_BUFFERHEADERTYPE*) * s->num_out_buffers);
    if (!s->in_buffer_headers || !s->free_in_buffers || !s->out_buffer_headers || !s->done_out_buffers)
        return AVERROR(ENOMEM);
    for (i = 0; i < s->num_in_buffers && err == OMX_ErrorNone; i++) {
        if (s->input_zerocopy)
            err = OMX_UseBuffer(s->handle, &s->in_buffer_headers[i], s->in_port, s, in_port_params.nBufferSize, NULL);
        else
            err = OMX_AllocateBuffer(s->handle, &s->in_buffer_headers[i],  s->in_port,  s, in_port_params.nBufferSize);
        if (err == OMX_ErrorNone)
            s->in_buffer_headers[i]->pAppPrivate = s->in_buffer_headers[i]->pOutputPortPrivate = NULL;
    }
    CHECK(err);
    s->num_in_buffers = i;
    for (i = 0; i < s->num_out_buffers && err == OMX_ErrorNone; i++)
        err = OMX_AllocateBuffer(s->handle, &s->out_buffer_headers[i], s->out_port, s, out_port_params.nBufferSize);
    CHECK(err);
    s->num_out_buffers = i;

    if (wait_for_state(s, OMX_StateIdle) < 0) {
        av_log(avctx, AV_LOG_ERROR, "Didn't get OMX_StateIdle\n");
        return AVERROR_UNKNOWN;
    }
    err = OMX_SendCommand(s->handle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
    CHECK(err);
    if (wait_for_state(s, OMX_StateExecuting) < 0) {
        av_log(avctx, AV_LOG_ERROR, "Didn't get OMX_StateExecuting\n");
        return AVERROR_UNKNOWN;
    }

    for (i = 0; i < s->num_out_buffers && err == OMX_ErrorNone; i++)
        err = OMX_FillThisBuffer(s->handle, s->out_buffer_headers[i]);
    if (err != OMX_ErrorNone) {
        for (; i < s->num_out_buffers; i++)
            s->done_out_buffers[s->num_done_out_buffers++] = s->out_buffer_headers[i];
    }
    for (i = 0; i < s->num_in_buffers; i++)
        s->free_in_buffers[s->num_free_in_buffers++] = s->in_buffer_headers[i];
    return err != OMX_ErrorNone ? AVERROR_UNKNOWN : 0;
}