/** This function is used to process the input buffer and provide one output buffer
  */
void omx_video_scheduler_component_BufferMgmtCallback(OMX_COMPONENTTYPE *openmaxStandComp, OMX_BUFFERHEADERTYPE* pInputBuffer, OMX_BUFFERHEADERTYPE* pOutputBuffer) {

  omx_video_scheduler_component_PrivateType*   omx_video_scheduler_component_Private = openmaxStandComp->pComponentPrivate;
  omx_base_video_PortType       *inPort = (omx_base_video_PortType *)omx_video_scheduler_component_Private->ports[OMX_BASE_FILTER_INPUTPORT_INDEX];
  omx_base_clock_PortType*        pClockPort;
  OMX_BOOL                        SendFrame;

  pClockPort  = (omx_base_clock_PortType*)omx_video_scheduler_component_Private->ports[CLOCKPORT_INDEX];
  if(PORT_IS_TUNNELED(pClockPort) && !PORT_IS_BEING_FLUSHED(inPort) &&
      (omx_video_scheduler_component_Private->transientState != OMX_TransStateExecutingToIdle) &&
      ((pInputBuffer->nFlags & OMX_BUFFERFLAG_EOS) != OMX_BUFFERFLAG_EOS)){
    SendFrame = omx_video_scheduler_component_ClockPortHandleFunction(omx_video_scheduler_component_Private, pInputBuffer);
    if(!SendFrame) pInputBuffer->nFilledLen = 0;
  }

  if((pInputBuffer->pBuffer != pOutputBuffer->pBuffer) && (pInputBuffer->nFilledLen > 0)){
    memcpy(pOutputBuffer->pBuffer,pInputBuffer->pBuffer,pInputBuffer->nFilledLen);
    pOutputBuffer->nOffset = pInputBuffer->nOffset;
  }
  pOutputBuffer->nFilledLen = pInputBuffer->nFilledLen;
  pInputBuffer->nFilledLen=0;
}
/** @brief Releases buffers under processing.
 * This function must be implemented in the derived classes, for the
 * specific processing
 */
OMX_ERRORTYPE clocksrc_port_FlushProcessingBuffers(omx_base_PortType *openmaxStandPort) {
  omx_clocksrc_component_PrivateType* omx_clocksrc_component_Private;
  OMX_BUFFERHEADERTYPE* pBuffer;
  int errQue;

  DEBUG(DEB_LEV_FUNCTION_NAME, "In %s\n", __func__);
  omx_clocksrc_component_Private = (omx_clocksrc_component_PrivateType*)openmaxStandPort->standCompContainer->pComponentPrivate;

  pthread_mutex_lock(&omx_clocksrc_component_Private->flush_mutex);
  openmaxStandPort->bIsPortFlushed=OMX_TRUE;
  /*Signal the buffer management thread of port flush,if it is waiting for buffers*/
  if(omx_clocksrc_component_Private->bMgmtSem->semval==0) {
    tsem_up(omx_clocksrc_component_Private->bMgmtSem);
  }
  tsem_up(omx_clocksrc_component_Private->clockEventSem);
  tsem_up(omx_clocksrc_component_Private->clockEventCompleteSem);

  if(omx_clocksrc_component_Private->state==OMX_StatePause ) {
    /*Waiting at paused state*/
    tsem_signal(omx_clocksrc_component_Private->bStateSem);
  }
  DEBUG(DEB_LEV_FULL_SEQ, "In %s waiting for flush all condition port index =%d\n", __func__,(int)openmaxStandPort->sPortParam.nPortIndex);
  /* Wait until flush is completed */
  pthread_mutex_unlock(&omx_clocksrc_component_Private->flush_mutex);
  tsem_down(omx_clocksrc_component_Private->flush_all_condition);

  tsem_reset(omx_clocksrc_component_Private->bMgmtSem);
  tsem_reset(omx_clocksrc_component_Private->clockEventSem);

  /* Flush all the buffers not under processing */
  while (openmaxStandPort->pBufferSem->semval > 0) {
    DEBUG(DEB_LEV_FULL_SEQ, "In %s TFlag=%x Flusing Port=%d,Semval=%d Qelem=%d\n",
    __func__,(int)openmaxStandPort->nTunnelFlags,(int)openmaxStandPort->sPortParam.nPortIndex,
    (int)openmaxStandPort->pBufferSem->semval,(int)openmaxStandPort->pBufferQueue->nelem);

    tsem_down(openmaxStandPort->pBufferSem);
    pBuffer = dequeue(openmaxStandPort->pBufferQueue);
    if (PORT_IS_TUNNELED(openmaxStandPort) && !PORT_IS_BUFFER_SUPPLIER(openmaxStandPort)) {
      DEBUG(DEB_LEV_FULL_SEQ, "In %s: Comp %s is returning io:%d buffer\n",
        __func__,omx_clocksrc_component_Private->name,(int)openmaxStandPort->sPortParam.nPortIndex);
      if (openmaxStandPort->sPortParam.eDir == OMX_DirInput) {
        ((OMX_COMPONENTTYPE*)(openmaxStandPort->hTunneledComponent))->FillThisBuffer(openmaxStandPort->hTunneledComponent, pBuffer);
      } else {
        ((OMX_COMPONENTTYPE*)(openmaxStandPort->hTunneledComponent))->EmptyThisBuffer(openmaxStandPort->hTunneledComponent, pBuffer);
      }
    } else if (PORT_IS_TUNNELED_N_BUFFER_SUPPLIER(openmaxStandPort)) {
        errQue = queue(openmaxStandPort->pBufferQueue,pBuffer);
        if (errQue) {
      	  /* /TODO the queue is full. This can be handled in a fine way with
      	   * some retrials, or other checking. For the moment this is a critical error
      	   * and simply causes the failure of this call
      	   */
      	  return OMX_ErrorInsufficientResources;
        }
    } else {
      (*(openmaxStandPort->BufferProcessedCallback))(
        openmaxStandPort->standCompContainer,
        omx_clocksrc_component_Private->callbackData,
        pBuffer);
    }
  }
  /*Port is tunneled and supplier and didn't received all it's buffer then wait for the buffers*/
  if (PORT_IS_TUNNELED_N_BUFFER_SUPPLIER(openmaxStandPort)) {
    while(openmaxStandPort->pBufferQueue->nelem!= openmaxStandPort->nNumAssignedBuffers){
      tsem_down(openmaxStandPort->pBufferSem);
      DEBUG(DEB_LEV_PARAMS, "In %s Got a buffer qelem=%d\n",__func__,openmaxStandPort->pBufferQueue->nelem);
    }
    tsem_reset(openmaxStandPort->pBufferSem);
  }

  pthread_mutex_lock(&omx_clocksrc_component_Private->flush_mutex);
  openmaxStandPort->bIsPortFlushed=OMX_FALSE;
  pthread_mutex_unlock(&omx_clocksrc_component_Private->flush_mutex);

  tsem_up(omx_clocksrc_component_Private->flush_condition);

  DEBUG(DEB_LEV_FULL_SEQ, "Out %s Port Index=%d bIsPortFlushed=%d Component %s\n", __func__,
    (int)openmaxStandPort->sPortParam.nPortIndex,(int)openmaxStandPort->bIsPortFlushed,omx_clocksrc_component_Private->name);

  DEBUG(DEB_LEV_PARAMS, "In %s TFlag=%x Qelem=%d BSem=%d bMgmtsem=%d component=%s\n", __func__,
    (int)openmaxStandPort->nTunnelFlags,
    (int)openmaxStandPort->pBufferQueue->nelem,
    (int)openmaxStandPort->pBufferSem->semval,
    (int)omx_clocksrc_component_Private->bMgmtSem->semval,
    omx_clocksrc_component_Private->name);

  DEBUG(DEB_LEV_FUNCTION_NAME, "Out %s Port Index=%d\n", __func__,(int)openmaxStandPort->sPortParam.nPortIndex);

  return OMX_ErrorNone;
}
void* omx_clocksrc_BufferMgmtFunction (void* param) {
  OMX_COMPONENTTYPE*                  openmaxStandComp = (OMX_COMPONENTTYPE*)param;
  omx_base_component_PrivateType*     omx_base_component_Private=(omx_base_component_PrivateType*)openmaxStandComp->pComponentPrivate;
  omx_clocksrc_component_PrivateType* omx_clocksrc_component_Private  = (omx_clocksrc_component_PrivateType*)omx_base_component_Private;
  omx_base_clock_PortType             *pOutPort[MAX_CLOCK_PORTS];
  tsem_t*                             pOutputSem[MAX_CLOCK_PORTS];
  queue_t*                            pOutputQueue[MAX_CLOCK_PORTS];
  OMX_BUFFERHEADERTYPE*               pOutputBuffer[MAX_CLOCK_PORTS];
  OMX_BOOL                            isOutputBufferNeeded[MAX_CLOCK_PORTS],bPortsBeingFlushed = OMX_FALSE;
  int                                 i,j,outBufExchanged[MAX_CLOCK_PORTS];

  for(i=0;i<omx_clocksrc_component_Private->sPortTypesParam[OMX_PortDomainOther].nPorts;i++) {
    pOutPort[i]             = (omx_base_clock_PortType *)omx_clocksrc_component_Private->ports[i];
    pOutputSem[i]           = pOutPort[i]->pBufferSem;
    pOutputQueue[i]         = pOutPort[i]->pBufferQueue;
    pOutputBuffer[i]        = NULL;
    isOutputBufferNeeded[i] = OMX_TRUE;
    outBufExchanged[i]      = 0;
  }

  DEBUG(DEB_LEV_FUNCTION_NAME, "In %s\n", __func__);
  while(omx_clocksrc_component_Private->state == OMX_StateIdle
         || omx_clocksrc_component_Private->state == OMX_StateExecuting
         || omx_clocksrc_component_Private->state == OMX_StatePause
         || omx_clocksrc_component_Private->transientState == OMX_TransStateLoadedToIdle){

    /*Wait till the ports are being flushed*/
    pthread_mutex_lock(&omx_clocksrc_component_Private->flush_mutex);
    for(i=0;i<omx_clocksrc_component_Private->sPortTypesParam[OMX_PortDomainOther].nPorts;i++) {
      bPortsBeingFlushed |= PORT_IS_BEING_FLUSHED(pOutPort[i]);
    }
    while(bPortsBeingFlushed) {
      pthread_mutex_unlock(&omx_clocksrc_component_Private->flush_mutex);
      for(i=0;i<omx_clocksrc_component_Private->sPortTypesParam[OMX_PortDomainOther].nPorts;i++) {
          if(isOutputBufferNeeded[i]==OMX_FALSE && PORT_IS_BEING_FLUSHED(pOutPort[i])) {
          pOutPort[i]->ReturnBufferFunction((omx_base_PortType*)pOutPort[i],pOutputBuffer[i]);
          outBufExchanged[i]--;
          pOutputBuffer[1]=NULL;
          isOutputBufferNeeded[i]=OMX_TRUE;
          DEBUG(DEB_LEV_FULL_SEQ, "Ports are flushing,so returning output buffer for port %i\n",i);
        }
      }

      tsem_up(omx_clocksrc_component_Private->flush_all_condition);
      tsem_down(omx_clocksrc_component_Private->flush_condition);
      pthread_mutex_lock(&omx_clocksrc_component_Private->flush_mutex);

      bPortsBeingFlushed = OMX_FALSE;
      for(i=0;i<omx_clocksrc_component_Private->sPortTypesParam[OMX_PortDomainOther].nPorts;i++) {
        bPortsBeingFlushed |= PORT_IS_BEING_FLUSHED(pOutPort[i]);
      }
    }
    pthread_mutex_unlock(&omx_clocksrc_component_Private->flush_mutex);

    /*Wait for clock state event*/
    DEBUG(DEB_LEV_SIMPLE_SEQ, "In %s Waiting for clock event\n",__func__);
    tsem_down(omx_clocksrc_component_Private->clockEventSem);
    DEBUG(DEB_LEV_SIMPLE_SEQ, "In %s clock event occured semval=%d \n",__func__,omx_clocksrc_component_Private->clockEventSem->semval);

    /*If port is not tunneled then simply return the buffer except paused state*/
    if(omx_clocksrc_component_Private->transientState == OMX_TransStatePauseToExecuting) {
      for(i=0;i<omx_clocksrc_component_Private->sPortTypesParam[OMX_PortDomainOther].nPorts;i++) {
        if(!PORT_IS_TUNNELED(pOutPort[i])) {

          if(pOutputSem[i]->semval>0 && isOutputBufferNeeded[i]==OMX_TRUE ) {
            tsem_down(pOutputSem[i]);
            if(pOutputQueue[i]->nelem>0){
              outBufExchanged[i]++;
              isOutputBufferNeeded[i]=OMX_FALSE;
              pOutputBuffer[i] = dequeue(pOutputQueue[i]);
              if(pOutputBuffer[i] == NULL){
                DEBUG(DEB_LEV_ERR, "Had NULL output buffer!!\n");
                break;
              }
            }
          }

          if(isOutputBufferNeeded[i]==OMX_FALSE) {
            /*Output Buffer has been produced or EOS. So, return output buffer and get new buffer*/
            if(pOutputBuffer[i]->nFilledLen!=0) {
              DEBUG(DEB_LEV_ERR, "In %s Returning Output nFilledLen=%d (line=%d)\n",
                __func__,(int)pOutputBuffer[i]->nFilledLen,__LINE__);
              pOutPort[i]->ReturnBufferFunction((omx_base_PortType*)pOutPort[i],pOutputBuffer[i]);
              outBufExchanged[i]--;
              pOutputBuffer[i]=NULL;
              isOutputBufferNeeded[i]=OMX_TRUE;
            }
          }
        }
      }
      omx_clocksrc_component_Private->transientState = OMX_TransStateMax;
    }

    if(omx_clocksrc_component_Private->state == OMX_StateLoaded  ||
       omx_clocksrc_component_Private->state == OMX_StateInvalid ||
       omx_clocksrc_component_Private->transientState == OMX_TransStateIdleToLoaded ||
       omx_clocksrc_component_Private->transientState == OMX_TransStateInvalid) {

      DEBUG(DEB_LEV_SIMPLE_SEQ, "In %s Buffer Management Thread is exiting (line %d)\n",__func__,__LINE__);
      break;
    }

    for(i=0;i<omx_clocksrc_component_Private->sPortTypesParam[OMX_PortDomainOther].nPorts;i++) {
      if(pOutPort[i]->sMediaTime.eUpdateType == OMX_TIME_UpdateClockStateChanged ||
         pOutPort[i]->sMediaTime.eUpdateType == OMX_TIME_UpdateScaleChanged      ||
         pOutPort[i]->sMediaTime.eUpdateType == OMX_TIME_UpdateRequestFulfillment) {

        if((isOutputBufferNeeded[i]==OMX_TRUE && pOutputSem[i]->semval==0) &&
          (omx_clocksrc_component_Private->state != OMX_StateLoaded && omx_clocksrc_component_Private->state != OMX_StateInvalid)
          && PORT_IS_ENABLED(pOutPort[i])) {
          //Signalled from EmptyThisBuffer or FillThisBuffer or some where else
          DEBUG(DEB_LEV_FULL_SEQ, "Waiting for next output buffer %i\n",i);
          tsem_down(omx_clocksrc_component_Private->bMgmtSem);
        }
        if(omx_clocksrc_component_Private->state == OMX_StateLoaded  ||
           omx_clocksrc_component_Private->state == OMX_StateInvalid ||
           omx_clocksrc_component_Private->transientState == OMX_TransStateIdleToLoaded ||
           omx_clocksrc_component_Private->transientState == OMX_TransStateInvalid) {
          DEBUG(DEB_LEV_SIMPLE_SEQ, "In %s Buffer Management Thread is exiting (line %d)\n",__func__,__LINE__);
          break;
        }

        if(pOutputSem[i]->semval>0 && isOutputBufferNeeded[i]==OMX_TRUE ) {
          tsem_down(pOutputSem[i]);
          if(pOutputQueue[i]->nelem>0){
            outBufExchanged[i]++;
            isOutputBufferNeeded[i]=OMX_FALSE;
            pOutputBuffer[i] = dequeue(pOutputQueue[i]);
            if(pOutputBuffer[i] == NULL){
              DEBUG(DEB_LEV_ERR, "Had NULL output buffer!!\n");
              break;
            }
          }
        } else {
          DEBUG(DEB_LEV_SIMPLE_SEQ, "In %s Output buffer not available Port %d (line=%d)\n",__func__,(int)i,__LINE__);

          /*Check if any dummy bMgmtSem signal and ports are flushing*/
          pthread_mutex_lock(&omx_clocksrc_component_Private->flush_mutex);
          bPortsBeingFlushed = OMX_FALSE;
          for(j=0;j<omx_clocksrc_component_Private->sPortTypesParam[OMX_PortDomainOther].nPorts;j++) {
            bPortsBeingFlushed |= PORT_IS_BEING_FLUSHED(pOutPort[j]);
          }
          pthread_mutex_unlock(&omx_clocksrc_component_Private->flush_mutex);
          if(bPortsBeingFlushed) {
            DEBUG(DEB_LEV_ERR, "In %s Ports are being flushed - breaking (line %d)\n",__func__,__LINE__);
            break;
          }
        }
        /*Process Output buffer of Port i */
        if(isOutputBufferNeeded[i]==OMX_FALSE) {
          if (omx_clocksrc_component_Private->BufferMgmtCallback) {
            (*(omx_clocksrc_component_Private->BufferMgmtCallback))(openmaxStandComp, pOutputBuffer[i]);
          } else {
            /*If no buffer management call back then don't produce any output buffer*/
            pOutputBuffer[i]->nFilledLen = 0;
          }

           /*Output Buffer has been produced or EOS. So, return output buffer and get new buffer*/
          if(pOutputBuffer[i]->nFilledLen!=0) {
            pOutPort[i]->ReturnBufferFunction((omx_base_PortType*)pOutPort[i],pOutputBuffer[i]);
            outBufExchanged[i]--;
            pOutputBuffer[i]=NULL;
            isOutputBufferNeeded[i]=OMX_TRUE;
          }
        }
      }
    }

    DEBUG(DEB_LEV_SIMPLE_SEQ, "Sent Clock Event for all ports\n");
    tsem_up(omx_clocksrc_component_Private->clockEventCompleteSem);
  }
  DEBUG(DEB_LEV_SIMPLE_SEQ,"Exiting Buffer Management Thread\n");
  return NULL;
}
/** @brief the entry point for sending buffers to the alsa sink port
 *
 * This function can be called by the EmptyThisBuffer or FillThisBuffer. It depends on
 * the nature of the port, that can be an input or output port.
 */
OMX_ERRORTYPE omx_alsasink_component_port_SendBufferFunction(omx_base_PortType *openmaxStandPort, OMX_BUFFERHEADERTYPE* pBuffer) {

  OMX_ERRORTYPE                   err;
  OMX_U32                         portIndex;
  OMX_COMPONENTTYPE*              omxComponent = openmaxStandPort->standCompContainer;
  omx_base_component_PrivateType* omx_base_component_Private = (omx_base_component_PrivateType*)omxComponent->pComponentPrivate;
  OMX_BOOL                        SendFrame;
  omx_base_clock_PortType*        pClockPort;
  int                             errQue;
#if NO_GST_OMX_PATCH
  unsigned int i;
#endif

  portIndex = (openmaxStandPort->sPortParam.eDir == OMX_DirInput)?pBuffer->nInputPortIndex:pBuffer->nOutputPortIndex;
  DEBUG(DEB_LEV_FUNCTION_NAME, "In %s portIndex %lu\n", __func__, portIndex);

  if (portIndex != openmaxStandPort->sPortParam.nPortIndex) {
    DEBUG(DEB_LEV_ERR, "In %s: wrong port for this operation portIndex=%d port->portIndex=%d\n",
           __func__, (int)portIndex, (int)openmaxStandPort->sPortParam.nPortIndex);
    return OMX_ErrorBadPortIndex;
  }

  if(omx_base_component_Private->state == OMX_StateInvalid) {
    DEBUG(DEB_LEV_ERR, "In %s: we are in OMX_StateInvalid\n", __func__);
    return OMX_ErrorInvalidState;
  }

  if(omx_base_component_Private->state != OMX_StateExecuting &&
    omx_base_component_Private->state != OMX_StatePause &&
    omx_base_component_Private->state != OMX_StateIdle) {
    DEBUG(DEB_LEV_ERR, "In %s: we are not in executing/paused/idle state, but in %d\n", __func__, omx_base_component_Private->state);
    return OMX_ErrorIncorrectStateOperation;
  }
  if (!PORT_IS_ENABLED(openmaxStandPort) || (PORT_IS_BEING_DISABLED(openmaxStandPort) && !PORT_IS_TUNNELED_N_BUFFER_SUPPLIER(openmaxStandPort)) ||
      (omx_base_component_Private->transientState == OMX_TransStateExecutingToIdle &&
      (PORT_IS_TUNNELED(openmaxStandPort) && !PORT_IS_BUFFER_SUPPLIER(openmaxStandPort)))) {
    DEBUG(DEB_LEV_ERR, "In %s: Port %d is disabled comp = %s \n", __func__, (int)portIndex,omx_base_component_Private->name);
    return OMX_ErrorIncorrectStateOperation;
  }

  /* Temporarily disable this check for gst-openmax */
#if NO_GST_OMX_PATCH
  {
  OMX_BOOL foundBuffer = OMX_FALSE;
  if(pBuffer!=NULL && pBuffer->pBuffer!=NULL) {
    for(i=0; i < openmaxStandPort->sPortParam.nBufferCountActual; i++){
    if (pBuffer->pBuffer == openmaxStandPort->pInternalBufferStorage[i]->pBuffer) {
      foundBuffer = OMX_TRUE;
      break;
    }
    }
  }
  if (!foundBuffer) {
    return OMX_ErrorBadParameter;
  }
  }
#endif

  if ((err = checkHeader(pBuffer, sizeof(OMX_BUFFERHEADERTYPE))) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "In %s: received wrong buffer header on input port\n", __func__);
    return err;
  }

  pClockPort  = (omx_base_clock_PortType*)omx_base_component_Private->ports[OMX_BASE_SINK_CLOCKPORT_INDEX];
  if(PORT_IS_TUNNELED(pClockPort) && !PORT_IS_BEING_FLUSHED(openmaxStandPort) &&
      (omx_base_component_Private->transientState != OMX_TransStateExecutingToIdle) &&
      ((pBuffer->nFlags & OMX_BUFFERFLAG_EOS) != OMX_BUFFERFLAG_EOS)){
    SendFrame = omx_alsasink_component_ClockPortHandleFunction((omx_alsasink_component_PrivateType*)omx_base_component_Private, pBuffer);
    /* drop the frame */
    if(!SendFrame) pBuffer->nFilledLen=0;
  }

  /* And notify the buffer management thread we have a fresh new buffer to manage */
  if(!PORT_IS_BEING_FLUSHED(openmaxStandPort) && !(PORT_IS_BEING_DISABLED(openmaxStandPort) && PORT_IS_TUNNELED_N_BUFFER_SUPPLIER(openmaxStandPort))){
      errQue = queue(openmaxStandPort->pBufferQueue, pBuffer);
      if (errQue) {
    	  /* /TODO the queue is full. This can be handled in a fine way with
    	   * some retrials, or other checking. For the moment this is a critical error
    	   * and simply causes the failure of this call
    	   */
    	  return OMX_ErrorInsufficientResources;
      }
      tsem_up(openmaxStandPort->pBufferSem);
      DEBUG(DEB_LEV_PARAMS, "In %s Signalling bMgmtSem Port Index=%d\n",__func__, (int)portIndex);
      tsem_up(omx_base_component_Private->bMgmtSem);
  }else if(PORT_IS_BUFFER_SUPPLIER(openmaxStandPort)){
      DEBUG(DEB_LEV_FULL_SEQ, "In %s: Comp %s received io:%d buffer\n",
        __func__,omx_base_component_Private->name,(int)openmaxStandPort->sPortParam.nPortIndex);
      errQue = queue(openmaxStandPort->pBufferQueue, pBuffer);
      if (errQue) {
    	  /* /TODO the queue is full. This can be handled in a fine way with
    	   * some retrials, or other checking. For the moment this is a critical error
    	   * and simply causes the failure of this call
    	   */
    	  return OMX_ErrorInsufficientResources;
      }
      tsem_up(openmaxStandPort->pBufferSem);
  }
  else { // If port being flushed and not tunneled then return error
    DEBUG(DEB_LEV_FULL_SEQ, "In %s \n", __func__);
    return OMX_ErrorIncorrectStateOperation;
  }
  return OMX_ErrorNone;
}
/** @brief the entry point for sending buffers to the port
 * 
 * This function can be called by the EmptyThisBuffer or FillThisBuffer. It depends on
 * the nature of the port, that can be an input or output port.
 */
OMX_ERRORTYPE base_clock_port_SendBufferFunction(
  omx_base_PortType *openmaxStandPort,
  OMX_BUFFERHEADERTYPE* pBuffer) {

  OMX_ERRORTYPE err;
  OMX_U32 portIndex;
  OMX_COMPONENTTYPE* omxComponent = openmaxStandPort->standCompContainer;
  omx_base_component_PrivateType* omx_base_component_Private = (omx_base_component_PrivateType*)omxComponent->pComponentPrivate;
#if NO_GST_OMX_PATCH
  unsigned int i;
#endif
  portIndex = (openmaxStandPort->sPortParam.eDir == OMX_DirInput)?pBuffer->nInputPortIndex:pBuffer->nOutputPortIndex;
  DEBUG(DEB_LEV_FUNCTION_NAME, "In %s portIndex %lu\n", __func__, portIndex);

  if (portIndex != openmaxStandPort->sPortParam.nPortIndex) {
    DEBUG(DEB_LEV_ERR, "In %s: wrong port for this operation portIndex=%d port->portIndex=%d\n", __func__, (int)portIndex, (int)openmaxStandPort->sPortParam.nPortIndex);
    return OMX_ErrorBadPortIndex;
  }

  if(omx_base_component_Private->state == OMX_StateInvalid) {
    DEBUG(DEB_LEV_ERR, "In %s: we are in OMX_StateInvalid\n", __func__);
    return OMX_ErrorInvalidState;
  }

  if(omx_base_component_Private->state != OMX_StateExecuting &&
    omx_base_component_Private->state != OMX_StatePause &&
    omx_base_component_Private->state != OMX_StateIdle) {
    DEBUG(DEB_LEV_ERR, "In %s: we are not in executing/paused/idle state, but in %d\n", __func__, omx_base_component_Private->state);
    return OMX_ErrorIncorrectStateOperation;
  }
  if (!PORT_IS_ENABLED(openmaxStandPort) || (PORT_IS_BEING_DISABLED(openmaxStandPort) && !PORT_IS_TUNNELED_N_BUFFER_SUPPLIER(openmaxStandPort)) ||
      (omx_base_component_Private->transientState == OMX_TransStateExecutingToIdle && 
      (PORT_IS_TUNNELED(openmaxStandPort) && !PORT_IS_BUFFER_SUPPLIER(openmaxStandPort)))) {
    DEBUG(DEB_LEV_ERR, "In %s: Port %d is disabled comp = %s \n", __func__, (int)portIndex,omx_base_component_Private->name);
    return OMX_ErrorIncorrectStateOperation;
  }

  /* Temporarily disable this check for gst-openmax */
#if NO_GST_OMX_PATCH
  {
  OMX_BOOL foundBuffer = OMX_FALSE;
  if(pBuffer!=NULL && pBuffer->pBuffer!=NULL) {
    for(i=0; i < openmaxStandPort->sPortParam.nBufferCountActual; i++){
    if (pBuffer->pBuffer == openmaxStandPort->pInternalBufferStorage[i]->pBuffer) {
      foundBuffer = OMX_TRUE;
      break;
    }
    }
  }
  if (!foundBuffer) {
    return OMX_ErrorBadParameter;
  }
  }
#endif

  if ((err = checkHeader(pBuffer, sizeof(OMX_BUFFERHEADERTYPE))) != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "In %s: received wrong buffer header on input port\n", __func__);
    return err;
  }
  /*If port is not tunneled then simply return the buffer except paused state*/
  if (!PORT_IS_TUNNELED(openmaxStandPort) && (omx_base_component_Private->state != OMX_StatePause)) {
    openmaxStandPort->ReturnBufferFunction(openmaxStandPort,pBuffer);
    return OMX_ErrorNone;
  }
  
  /* And notify the buffer management thread we have a fresh new buffer to manage */
  if(!PORT_IS_BEING_FLUSHED(openmaxStandPort) && !(PORT_IS_BEING_DISABLED(openmaxStandPort) && PORT_IS_TUNNELED_N_BUFFER_SUPPLIER(openmaxStandPort))){
    queue(openmaxStandPort->pBufferQueue, pBuffer);
    tsem_up(openmaxStandPort->pBufferSem);
    DEBUG(DEB_LEV_PARAMS, "In %s Signalling bMgmtSem Port Index=%d\n",__func__, (int)portIndex);
    tsem_up(omx_base_component_Private->bMgmtSem);
  }else if(PORT_IS_BUFFER_SUPPLIER(openmaxStandPort)){
    DEBUG(DEB_LEV_FULL_SEQ, "In %s: Comp %s received io:%d buffer\n", 
        __func__,omx_base_component_Private->name,(int)openmaxStandPort->sPortParam.nPortIndex);
    queue(openmaxStandPort->pBufferQueue, pBuffer);
    tsem_up(openmaxStandPort->pBufferSem);
  }
  else { // If port being flushed and not tunneled then return error
    DEBUG(DEB_LEV_FULL_SEQ, "In %s \n", __func__);
    return OMX_ErrorIncorrectStateOperation;
  }
  return OMX_ErrorNone;
}
/**
 * Returns Input/Output Buffer to the IL client or Tunneled Component
 */
OMX_ERRORTYPE videoenc_port_ReturnBufferFunction(
	omx_base_PortType *openmaxStandPort,
	OMX_BUFFERHEADERTYPE *pBuffer)
{
	int errQue;
	OMX_ERRORTYPE eError = OMX_ErrorNone;
	omx_base_component_PrivateType *omx_base_component_Private = openmaxStandPort->standCompContainer->pComponentPrivate;
	omx_videoenc_PortType *omx_videoenc_Port = (omx_videoenc_PortType *)openmaxStandPort;
	queue_t *pQueue = omx_videoenc_Port->pBufferQueue;
	tsem_t *pSem = omx_videoenc_Port->pBufferSem;
	OMX_VCE_Buffers_List *pBuffersMng_List= &(omx_videoenc_Port->BuffersMng_List);
	
	DEBUG(DEB_LEV_FUNCTION_NAME, "In %s for port %p\n", __func__, omx_videoenc_Port);
	
	OMX_BUFFERHEADERTYPE *pBuffer_ACTEXT =  (OMX_BUFFERHEADERTYPE *)pBuffer;
	if( omx_videoenc_Port->sPortParam.eDir == OMX_DirOutput )
	{
		eError = ReturnBuffer_BuffersMng(pBuffersMng_List, pBuffer_ACTEXT, omx_videoenc_Port->bIsStoreMediaData);
		if(eError != OMX_ErrorNone)
		{
			DEBUG(DEB_LEV_ERR, "err!ReturnBuffer_BuffersMng fail!%s,%d\n",__FILE__,__LINE__);
			return eError;
		}
	}

#ifdef enable_gralloc
	if(pBuffer->nFilledLen == 0 && ((pBuffer->nFlags & OMX_BUFFERFLAG_EOS) == OMX_BUFFERFLAG_EOS) )
	{
		DEBUG(DEB_LEV_ERR, "ReturnBufferFunction,input buffer is eos now!");
	}
	else 
	{
		eError = UnLock_VirAddr_BuffersMng(pBuffersMng_List, pBuffer_ACTEXT, omx_videoenc_Port->bIsStoreMediaData);
		if(eError != OMX_ErrorNone)
		{
			DEBUG(DEB_LEV_ERR, "err!UnLock_VirAddr_BuffersMng fail!%s,%d\n", __FILE__, __LINE__);
			return eError;
		}
	}
#endif

	if (PORT_IS_TUNNELED(omx_videoenc_Port) &&
		! PORT_IS_BUFFER_SUPPLIER(omx_videoenc_Port))
	{
		if (omx_videoenc_Port->sPortParam.eDir == OMX_DirInput)
		{
			pBuffer->nOutputPortIndex = omx_videoenc_Port->nTunneledPort;
			pBuffer->nInputPortIndex = omx_videoenc_Port->sPortParam.nPortIndex;
			eError = ((OMX_COMPONENTTYPE *)(omx_videoenc_Port->hTunneledComponent))->FillThisBuffer(omx_videoenc_Port->hTunneledComponent, pBuffer);
			if(eError != OMX_ErrorNone)
			{
				DEBUG(DEB_LEV_ERR, "In %s eError %08x in FillThis Buffer from Component %s Non-Supplier\n",
					__func__, eError,omx_base_component_Private->name);
			}
		}
		else
		{
			pBuffer->nInputPortIndex = omx_videoenc_Port->nTunneledPort;
			pBuffer->nOutputPortIndex = omx_videoenc_Port->sPortParam.nPortIndex;
			eError = ((OMX_COMPONENTTYPE *)(omx_videoenc_Port->hTunneledComponent))->EmptyThisBuffer(omx_videoenc_Port->hTunneledComponent, pBuffer);
			if(eError != OMX_ErrorNone) {
				DEBUG(DEB_LEV_ERR, "In %s eError %08x in EmptyThis Buffer from Component %s Non-Supplier\n",
					__func__, eError, omx_base_component_Private->name);
			}
		}
	}
	else if (PORT_IS_TUNNELED_N_BUFFER_SUPPLIER(omx_videoenc_Port) &&
		!PORT_IS_BEING_FLUSHED(omx_videoenc_Port))
	{
		if (omx_videoenc_Port->sPortParam.eDir == OMX_DirInput)
		{
			eError = ((OMX_COMPONENTTYPE *)(omx_videoenc_Port->hTunneledComponent))->FillThisBuffer(omx_videoenc_Port->hTunneledComponent, pBuffer);
			if(eError != OMX_ErrorNone)
			{
				DEBUG(DEB_LEV_FULL_SEQ, "In %s eError %08x in FillThis Buffer from Component %s Supplier\n",
					__func__, eError,omx_base_component_Private->name);
				/*If Error Occured then queue the buffer*/
				errQue = queue(pQueue, pBuffer);
				if (errQue)
				{
					/* /TODO the queue is full. This can be handled in a fine way with
					* some retrials, or other checking. For the moment this is a critical error
					* and simply causes the failure of this call
					*/
					return OMX_ErrorInsufficientResources;
				}

				tsem_up(pSem);
			}
		}
		else
		{
			eError = ((OMX_COMPONENTTYPE *)(omx_videoenc_Port->hTunneledComponent))->EmptyThisBuffer(omx_videoenc_Port->hTunneledComponent, pBuffer);
			if(eError != OMX_ErrorNone) {
				DEBUG(DEB_LEV_FULL_SEQ, "In %s eError %08x in EmptyThis Buffer from Component %s Supplier\n",
					__func__, eError,omx_base_component_Private->name);
				/*If Error Occured then queue the buffer*/
				errQue = queue(pQueue, pBuffer);
				if (errQue) {
					/* /TODO the queue is full. This can be handled in a fine way with
					* some retrials, or other checking. For the moment this is a critical error
					* and simply causes the failure of this call
					*/
					return OMX_ErrorInsufficientResources;
				}
				tsem_up(pSem);
			}
		}
	}
	else if (!PORT_IS_TUNNELED(omx_videoenc_Port))
	{
		//here
		(*(omx_videoenc_Port->BufferProcessedCallback))(
			omx_videoenc_Port->standCompContainer,
			omx_base_component_Private->callbackData,
			pBuffer);
	}
	else
	{
		errQue = queue(pQueue, pBuffer);
		if (errQue)
		{
			/* /TODO the queue is full. This can be handled in a fine way with
			* some retrials, or other checking. For the moment this is a critical error
			* and simply causes the failure of this call
			*/
			return OMX_ErrorInsufficientResources;
		}
		omx_videoenc_Port->nNumBufferFlushed++;
	}

	DEBUG(DEB_LEV_FUNCTION_NAME, "Out of %s for port %p\n", __func__, omx_videoenc_Port);
	return OMX_ErrorNone;
}
/** @brief the entry point for sending buffers to the port
 *
 * This function can be called by the EmptyThisBuffer or FillThisBuffer. It depends on
 * the nature of the port, that can be an input or output port.
 */
OMX_ERRORTYPE videoenc_port_SendBufferFunction(
	omx_base_PortType *openmaxStandPort,
	OMX_BUFFERHEADERTYPE *pBuffer)
{
	int errQue;
	OMX_U32 portIndex;
	OMX_ERRORTYPE err = OMX_ErrorNone;
	OMX_COMPONENTTYPE *omxComponent = openmaxStandPort->standCompContainer;
	omx_videoenc_PortType *omx_videoenc_Port = (omx_videoenc_PortType *)openmaxStandPort;
	omx_base_component_PrivateType *omx_base_component_Private = (omx_base_component_PrivateType *)omxComponent->pComponentPrivate;
	OMX_VCE_Buffers_List *pBuffersMng_List= &(omx_videoenc_Port->BuffersMng_List);
	DEBUG(DEB_LEV_FUNCTION_NAME, "In %s for port %p\n", __func__, omx_videoenc_Port);
#if NO_GST_OMX_PATCH
	unsigned int i;
#endif
	portIndex = (omx_videoenc_Port->sPortParam.eDir == OMX_DirInput) ? pBuffer->nInputPortIndex : pBuffer->nOutputPortIndex;
	DEBUG(DEB_LEV_FUNCTION_NAME, "In %s portIndex %d\n", __func__, portIndex);

	if (portIndex != omx_videoenc_Port->sPortParam.nPortIndex)
	{
		DEBUG(DEB_LEV_ERR, "In %s: wrong port for this operation portIndex=%d port->portIndex=%d\n", __func__, (int)portIndex,
			(int)omx_videoenc_Port->sPortParam.nPortIndex);
		return OMX_ErrorBadPortIndex;
	}

	if(omx_base_component_Private->state == OMX_StateInvalid)
	{
		DEBUG(DEB_LEV_ERR, "In %s: we are in OMX_StateInvalid\n", __func__);
		return OMX_ErrorInvalidState;
	}

	if(omx_base_component_Private->state != OMX_StateExecuting &&
		omx_base_component_Private->state != OMX_StatePause &&
		omx_base_component_Private->state != OMX_StateIdle)
	{
		DEBUG(DEB_LEV_ERR, "In %s: we are not in executing/paused/idle state, but in %d\n", __func__, omx_base_component_Private->state);
		return OMX_ErrorIncorrectStateOperation;
	}

	if (!PORT_IS_ENABLED(omx_videoenc_Port) || (PORT_IS_BEING_DISABLED(omx_videoenc_Port) && !PORT_IS_TUNNELED_N_BUFFER_SUPPLIER(omx_videoenc_Port)) ||
		((omx_base_component_Private->transientState == OMX_TransStateExecutingToIdle ||
		omx_base_component_Private->transientState == OMX_TransStatePauseToIdle) &&
		(PORT_IS_TUNNELED(omx_videoenc_Port) && !PORT_IS_BUFFER_SUPPLIER(omx_videoenc_Port))))
	{
		DEBUG(DEB_LEV_ERR, "In %s: Port %d is disabled comp = %s \n", __func__, (int)portIndex, omx_base_component_Private->name);
		return OMX_ErrorIncorrectStateOperation;
	}

	/* Temporarily disable this check for gst-openmax */
#if NO_GST_OMX_PATCH
	{
		OMX_BOOL foundBuffer = OMX_FALSE;
		if(pBuffer!=NULL && pBuffer->pBuffer!=NULL)
		{
			for(i=0; i < omx_videoenc_Port->sPortParam.nBufferCountActual; i++)
			{
				if (pBuffer->pBuffer == omx_videoenc_Port->pInternalBufferStorage[i]->pBuffer)
				{
					foundBuffer = OMX_TRUE;
					break;
				}
			}
		}
		if (!foundBuffer)
		{
			return OMX_ErrorBadParameter;
		}
	}
#endif

	if ((err = checkHeader(pBuffer, sizeof(OMX_BUFFERHEADERTYPE))) != OMX_ErrorNone)
	{
		DEBUG(DEB_LEV_ERR, "In %s: received wrong buffer header on input port\n", __func__);
		return err;
	}

	/* And notify the buffer management thread we have a fresh new buffer to manage */
	if(!PORT_IS_BEING_FLUSHED(omx_videoenc_Port) && \
		!(PORT_IS_BEING_DISABLED(omx_videoenc_Port) && PORT_IS_TUNNELED_N_BUFFER_SUPPLIER(omx_videoenc_Port)))
	{
		//here
		if(omx_videoenc_Port->bIsStoreMediaData == OMX_TRUE)
		{
			if((*(OMX_U32 *)pBuffer->pBuffer != kMetadataBufferTypeCameraSource_act) && \
				(*(OMX_U32 *)pBuffer->pBuffer != kMetadataBufferTypeGrallocSource_act))
			{
				DEBUG(DEB_LEV_ERR, "Warning!in StoreMediaData mode,but the buffer (%x) is not kMetadataBufferTypeCameraSource_act!\n",
					(int)*(OMX_U32 *)pBuffer->pBuffer);
			}
		}

		if(omx_videoenc_Port->ringbuffer == OMX_TRUE && omx_videoenc_Port->sPortParam.nPortIndex == OMX_BASE_FILTER_OUTPUTPORT_INDEX)
		{
			err = Free_UseRingBuffer_BuffersMng(&omx_videoenc_Port->BuffersMng_List,omx_videoenc_Port->bufferpool,pBuffer,
				omx_videoenc_Port->sPortParam.nBufferSize);
			if( err != OMX_ErrorNone)
			{
				DEBUG(DEB_LEV_ERR, "err!In %s: SendBuffer_BuffersMng\n", __func__);
				return err;
			}
		}
		else
		{
			err = SendBuffer_BuffersMng(pBuffersMng_List,pBuffer,omx_videoenc_Port->bIsStoreMediaData,omx_videoenc_Port->sPortParam.eDir);
			if( err != OMX_ErrorNone)
			{
				DEBUG(DEB_LEV_ERR, "err!In %s: SendBuffer_BuffersMng\n", __func__);
				return err;
			}
		}

		errQue = queue(omx_videoenc_Port->pBufferQueue, pBuffer);
		if (errQue)
		{
			/* /TODO the queue is full. This can be handled in a fine way with
			* some retrials, or other checking. For the moment this is a critical error
			* and simply causes the failure of this call
			*/
			return OMX_ErrorInsufficientResources;
		}

		tsem_up(omx_videoenc_Port->pBufferSem);
		DEBUG(DEB_LEV_PARAMS, "In %s Signalling bMgmtSem Port Index=%d\n", __func__, (int)portIndex);
		tsem_up(omx_base_component_Private->bMgmtSem);
	}
	else if(PORT_IS_BUFFER_SUPPLIER(omx_videoenc_Port))
	{
		DEBUG(DEB_LEV_FULL_SEQ, "In %s: Comp %s received io:%d buffer\n",
			__func__, omx_base_component_Private->name, (int)omx_videoenc_Port->sPortParam.nPortIndex);

		errQue = queue(omx_videoenc_Port->pBufferQueue, pBuffer);
		if (errQue)
		{
			/* /TODO the queue is full. This can be handled in a fine way with
			* some retrials, or other checking. For the moment this is a critical error
			* and simply causes the failure of this call
			*/
			return OMX_ErrorInsufficientResources;
		}
		tsem_up(omx_videoenc_Port->pBufferSem);
	}
	else
	{
		// If port being flushed and not tunneled then return error
		DEBUG(DEB_LEV_FULL_SEQ, "In %s \n", __func__);
		return OMX_ErrorIncorrectStateOperation;
	}

	DEBUG(DEB_LEV_FUNCTION_NAME, "Out of %s for port %p\n", __func__, omx_videoenc_Port);
	return OMX_ErrorNone;
}