gst_qtdemux_chain (GstPad * sinkpad, GstBuffer * inbuf)
{
  GstQTDemux *demux;
  GstFlowReturn ret = GST_FLOW_OK;

  demux = GST_QTDEMUX (gst_pad_get_parent (sinkpad));

  gst_adapter_push (demux->adapter, inbuf);

  GST_DEBUG_OBJECT (demux, "pushing in inbuf %p, neededbytes:%u, available:%u",
      inbuf, demux->neededbytes, gst_adapter_available (demux->adapter));

  while (((gst_adapter_available (demux->adapter)) >= demux->neededbytes) &&
      (ret == GST_FLOW_OK)) {

    GST_DEBUG_OBJECT (demux,
        "state:%d , demux->neededbytes:%d, demux->offset:%lld", demux->state,
        demux->neededbytes, demux->offset);

    switch (demux->state) {
      case QTDEMUX_STATE_INITIAL:{
        const guint8 *data;
        guint32 fourcc;
        guint64 size;

        data = gst_adapter_peek (demux->adapter, demux->neededbytes);

        /* get fourcc/length, set neededbytes */
        extract_initial_length_and_fourcc ((guint8 *) data, &size, &fourcc);
        GST_DEBUG_OBJECT (demux,
            "Peeking found [%" GST_FOURCC_FORMAT "] size: %u",
            GST_FOURCC_ARGS (fourcc), (guint) size);
        if (size == 0) {
          GST_ELEMENT_ERROR (demux, STREAM, DECODE,
              (_("This file is invalid and cannot be played.")),
              ("initial atom '%" GST_FOURCC_FORMAT "' has empty length",
                  GST_FOURCC_ARGS (fourcc)));
          ret = GST_FLOW_ERROR;
          break;
        }
        if (fourcc == FOURCC_mdat) {
          if (demux->n_streams > 0) {
            demux->state = QTDEMUX_STATE_MOVIE;
            demux->neededbytes = next_entry_size (demux);
          } else {
            demux->state = QTDEMUX_STATE_BUFFER_MDAT;
            demux->neededbytes = size;
            demux->mdatoffset = demux->offset;
          }
        } else {
          demux->neededbytes = size;
          demux->state = QTDEMUX_STATE_HEADER;
        }
        break;
      }
      case QTDEMUX_STATE_HEADER:{
        guint8 *data;
        guint32 fourcc;

        GST_DEBUG_OBJECT (demux, "In header");

        data = gst_adapter_take (demux->adapter, demux->neededbytes);

        /* parse the header */
        extract_initial_length_and_fourcc (data, NULL, &fourcc);
        if (fourcc == FOURCC_moov) {
          GST_DEBUG_OBJECT (demux, "Parsing [moov]");

          qtdemux_parse_moov (demux, data, demux->neededbytes);
          qtdemux_node_dump (demux, demux->moov_node);
          qtdemux_parse_tree (demux);

          g_node_destroy (demux->moov_node);
          g_free (data);
          demux->moov_node = NULL;
        } else {
          GST_WARNING_OBJECT (demux,
              "Unknown fourcc while parsing header : %" GST_FOURCC_FORMAT,
              GST_FOURCC_ARGS (fourcc));
          /* Let's jump that one and go back to initial state */
        }

        GST_DEBUG_OBJECT (demux, "Finished parsing the header");
        if (demux->mdatbuffer && demux->n_streams) {
          /* the mdat was before the header */
          GST_DEBUG_OBJECT (demux, "We have n_streams:%d and mdatbuffer:%p",
              demux->n_streams, demux->mdatbuffer);
          gst_adapter_clear (demux->adapter);
          GST_DEBUG_OBJECT (demux, "mdatbuffer starts with %" GST_FOURCC_FORMAT,
              GST_FOURCC_ARGS (QT_UINT32 (demux->mdatbuffer)));
          gst_adapter_push (demux->adapter, demux->mdatbuffer);
          demux->mdatbuffer = NULL;
          demux->offset = demux->mdatoffset;
          demux->neededbytes = next_entry_size (demux);
          demux->state = QTDEMUX_STATE_MOVIE;
        } else {
          GST_DEBUG_OBJECT (demux, "Carrying on normally");
          demux->offset += demux->neededbytes;
          demux->neededbytes = 16;
          demux->state = QTDEMUX_STATE_INITIAL;
        }

        break;
      }
      case QTDEMUX_STATE_BUFFER_MDAT:{
        GST_DEBUG_OBJECT (demux, "Got our buffer at offset %lld",
            demux->mdatoffset);
        if (demux->mdatbuffer)
          gst_buffer_unref (demux->mdatbuffer);
        demux->mdatbuffer = gst_buffer_new ();
        gst_buffer_set_data (demux->mdatbuffer,
            gst_adapter_take (demux->adapter, demux->neededbytes),
            demux->neededbytes);
        GST_DEBUG_OBJECT (demux, "mdatbuffer starts with %" GST_FOURCC_FORMAT,
            GST_FOURCC_ARGS (QT_UINT32 (demux->mdatbuffer)));
        demux->offset += demux->neededbytes;
        demux->neededbytes = 16;
        demux->state = QTDEMUX_STATE_INITIAL;
        gst_qtdemux_post_progress (demux, 1, 1);

        break;
      }
      case QTDEMUX_STATE_MOVIE:{
        guint8 *data;
        GstBuffer *outbuf;
        QtDemuxStream *stream = NULL;
        int i = -1;

        GST_DEBUG_OBJECT (demux, "BEGIN // in MOVIE for offset %lld",
            demux->offset);

        if (demux->todrop) {
          gst_adapter_flush (demux->adapter, demux->todrop);
          demux->neededbytes -= demux->todrop;
          demux->offset += demux->todrop;
        }

        /* Figure out which stream this is packet belongs to */
        for (i = 0; i < demux->n_streams; i++) {
          stream = demux->streams[i];
          GST_LOG_OBJECT (demux,
              "Checking stream %d (sample_index:%d / offset:%lld / size:%d / chunk:%d)",
              i, stream->sample_index,
              stream->samples[stream->sample_index].offset,
              stream->samples[stream->sample_index].size,
              stream->samples[stream->sample_index].chunk);

          if (stream->samples[stream->sample_index].offset == demux->offset)
            break;
        }

        if (stream == NULL)
          goto unknown_stream;

        /* first buffer? */
        /* FIXME : this should be handled in sink_event */
        if (demux->last_ts == GST_CLOCK_TIME_NONE) {
          gst_qtdemux_push_event (demux,
              gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_TIME,
                  0, GST_CLOCK_TIME_NONE, 0));
        }

        /* get data */
        data = gst_adapter_take (demux->adapter, demux->neededbytes);

        /* Put data in a buffer, set timestamps, caps, ... */
        outbuf = gst_buffer_new ();
        gst_buffer_set_data (outbuf, data, demux->neededbytes);
        GST_DEBUG_OBJECT (demux, "stream : %" GST_FOURCC_FORMAT,
            GST_FOURCC_ARGS (stream->fourcc));

        if (stream->samples[stream->sample_index].pts_offset) {
          demux->last_ts = stream->samples[stream->sample_index].timestamp;
          GST_BUFFER_TIMESTAMP (outbuf) = demux->last_ts +
              stream->samples[stream->sample_index].pts_offset;
        } else {
          GST_BUFFER_TIMESTAMP (outbuf) =
              stream->samples[stream->sample_index].timestamp;
          demux->last_ts = GST_BUFFER_TIMESTAMP (outbuf);
        }
        GST_BUFFER_DURATION (outbuf) =
            stream->samples[stream->sample_index].duration;

        /* send buffer */
        if (stream->pad) {
          GST_LOG_OBJECT (demux,
              "Pushing buffer with time %" GST_TIME_FORMAT " on pad %p",
              GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)), stream->pad);
          gst_buffer_set_caps (outbuf, stream->caps);
          ret = gst_pad_push (stream->pad, outbuf);
        } else {
          gst_buffer_unref (outbuf);
          ret = GST_FLOW_OK;
        }

        /* combine flows */
        ret = gst_qtdemux_combine_flows (demux, stream, ret);

        stream->sample_index++;

        /* update current offset and figure out size of next buffer */
        GST_LOG_OBJECT (demux, "increasing offset %" G_GUINT64_FORMAT " by %u",
            demux->offset, demux->neededbytes);
        demux->offset += demux->neededbytes;
        GST_LOG_OBJECT (demux, "offset is now %lld", demux->offset);

        if ((demux->neededbytes = next_entry_size (demux)) == -1)
          goto eos;
        break;
      }
      default:
        goto invalid_state;
    }
  }

  /* when buffering movie data, at least show user something is happening */
  if (ret == GST_FLOW_OK && demux->state == QTDEMUX_STATE_BUFFER_MDAT &&
      gst_adapter_available (demux->adapter) <= demux->neededbytes) {
    gst_qtdemux_post_progress (demux, gst_adapter_available (demux->adapter),
        demux->neededbytes);
  }
done:
  gst_object_unref (demux);

  return ret;

  /* ERRORS */
unknown_stream:
  {
    GST_ELEMENT_ERROR (demux, STREAM, FAILED, (NULL), ("unknown stream found"));
    ret = GST_FLOW_ERROR;
    goto done;
  }
eos:
  {
    GST_DEBUG_OBJECT (demux, "no next entry, EOS");
    ret = GST_FLOW_UNEXPECTED;
    goto done;
  }
invalid_state:
  {
    GST_ELEMENT_ERROR (demux, STREAM, FAILED,
        (NULL), ("qtdemuxer invalid state %d", demux->state));
    ret = GST_FLOW_ERROR;
    goto done;
  }
}


MagickExport ImageType IdentifyImageGray(const Image *image,
  ExceptionInfo *exception)
{
  CacheView
    *image_view;

  ImageType
    type;

  register const PixelPacket
    *p;

  register ssize_t
    x;

  ssize_t
    y;

  assert(image != (Image *) NULL);
  assert(image->signature == MagickSignature);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  if ((image->type == BilevelType) || (image->type == GrayscaleType) ||
      (image->type == GrayscaleMatteType))
    return(image->type);
  if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
    return(UndefinedType);
  type=BilevelType;
  image_view=AcquireVirtualCacheView(image,exception);
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
    if (p == (const PixelPacket *) NULL)
      break;
    for (x=0; x < (ssize_t) image->columns; x++)
    {
      if (IsPixelGray(p) == MagickFalse)
        {
          type=UndefinedType;
          break;
        }
      if ((type == BilevelType) && (IsPixelMonochrome(p) == MagickFalse))
        type=GrayscaleType;
      p++;
    }
    if (type == UndefinedType)
      break;
  }
  image_view=DestroyCacheView(image_view);
  if ((type == GrayscaleType) && (image->matte != MagickFalse))
    type=GrayscaleMatteType;
  return(type);
}


OMX_ERRORTYPE  omx_venc::set_parameter(OMX_IN OMX_HANDLETYPE     hComp,
        OMX_IN OMX_INDEXTYPE paramIndex,
        OMX_IN OMX_PTR        paramData)
{
 (void)hComp;
    OMX_ERRORTYPE eRet = OMX_ErrorNone;

 if (m_state == OMX_StateInvalid) {
        DEBUG_PRINT_ERROR("ERROR: Set Param in Invalid State");
 return OMX_ErrorInvalidState;
 }
 if (paramData == NULL) {
        DEBUG_PRINT_ERROR("ERROR: Get Param in Invalid paramData");
 return OMX_ErrorBadParameter;
 }

 /*set_parameter can be called in loaded state
      or disabled port */
 if (m_state == OMX_StateLoaded
 || m_sInPortDef.bEnabled == OMX_FALSE
 || m_sOutPortDef.bEnabled == OMX_FALSE) {
        DEBUG_PRINT_LOW("Set Parameter called in valid state");
 } else {
        DEBUG_PRINT_ERROR("ERROR: Set Parameter called in Invalid State");
 return OMX_ErrorIncorrectStateOperation;
 }

 switch ((int)paramIndex) {
 case OMX_IndexParamPortDefinition:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_PORTDEFINITIONTYPE);
                OMX_PARAM_PORTDEFINITIONTYPE *portDefn;
                portDefn = (OMX_PARAM_PORTDEFINITIONTYPE *) paramData;
                DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition H= %d, W = %d",
 (int)portDefn->format.video.nFrameHeight,
 (int)portDefn->format.video.nFrameWidth);

 if (PORT_INDEX_IN == portDefn->nPortIndex) {
 if (!dev_is_video_session_supported(portDefn->format.video.nFrameWidth,
                                portDefn->format.video.nFrameHeight)) {
                        DEBUG_PRINT_ERROR("video session not supported");
                        omx_report_unsupported_setting();
 return OMX_ErrorUnsupportedSetting;
 }

                     DEBUG_PRINT_LOW("i/p actual cnt requested = %u", (unsigned int)portDefn->nBufferCountActual);
                     DEBUG_PRINT_LOW("i/p min cnt requested = %u", (unsigned int)portDefn->nBufferCountMin);
                     DEBUG_PRINT_LOW("i/p buffersize requested = %u", (unsigned int)portDefn->nBufferSize);
                    if (portDefn->nBufferCountActual > MAX_NUM_INPUT_BUFFERS) {
                        DEBUG_PRINT_ERROR("ERROR: (In_PORT) actual count (%u) exceeds max(%u)",
                                (unsigned int)portDefn->nBufferCountActual, (unsigned int)MAX_NUM_INPUT_BUFFERS);
                        return OMX_ErrorUnsupportedSetting;
                    }
                     if (portDefn->nBufferCountMin > portDefn->nBufferCountActual) {
                         DEBUG_PRINT_ERROR("ERROR: (In_PORT) Min buffers (%u) > actual count (%u)",
                                 (unsigned int)portDefn->nBufferCountMin, (unsigned int)portDefn->nBufferCountActual);
 return OMX_ErrorUnsupportedSetting;
 }
 if (handle->venc_set_param(paramData,OMX_IndexParamPortDefinition) != true) {
                        DEBUG_PRINT_ERROR("ERROR: venc_set_param input failed");
 return handle->hw_overload ? OMX_ErrorInsufficientResources :
                                OMX_ErrorUnsupportedSetting;
 }

                    DEBUG_PRINT_LOW("i/p previous actual cnt = %u", (unsigned int)m_sInPortDef.nBufferCountActual);
                    DEBUG_PRINT_LOW("i/p previous min cnt = %u", (unsigned int)m_sInPortDef.nBufferCountMin);
                    memcpy(&m_sInPortDef, portDefn,sizeof(OMX_PARAM_PORTDEFINITIONTYPE));

#ifdef _ANDROID_ICS_
 if (portDefn->format.video.eColorFormat ==
 (OMX_COLOR_FORMATTYPE)QOMX_COLOR_FormatAndroidOpaque) {
                        m_sInPortDef.format.video.eColorFormat = (OMX_COLOR_FORMATTYPE)
                            QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m;
 if (!mUseProxyColorFormat) {
 if (!c2d_conv.init()) {
                                DEBUG_PRINT_ERROR("C2D init failed");
 return OMX_ErrorUnsupportedSetting;
 }
                            DEBUG_PRINT_HIGH("C2D init is successful");
 }
                        mUseProxyColorFormat = true;
                        m_input_msg_id = OMX_COMPONENT_GENERATE_ETB_OPQ;
 } else
                        mUseProxyColorFormat = false;
#endif
 /*Query Input Buffer Requirements*/
                    dev_get_buf_req   (&m_sInPortDef.nBufferCountMin,
 &m_sInPortDef.nBufferCountActual,
 &m_sInPortDef.nBufferSize,
                            m_sInPortDef.nPortIndex);

 /*Query ouput Buffer Requirements*/
                    dev_get_buf_req   (&m_sOutPortDef.nBufferCountMin,
 &m_sOutPortDef.nBufferCountActual,
 &m_sOutPortDef.nBufferSize,
                            m_sOutPortDef.nPortIndex);
                    m_sInPortDef.nBufferCountActual = portDefn->nBufferCountActual;
 } else if (PORT_INDEX_OUT == portDefn->nPortIndex) {

                     DEBUG_PRINT_LOW("o/p actual cnt requested = %u", (unsigned int)portDefn->nBufferCountActual);
                     DEBUG_PRINT_LOW("o/p min cnt requested = %u", (unsigned int)portDefn->nBufferCountMin);
                     DEBUG_PRINT_LOW("o/p buffersize requested = %u", (unsigned int)portDefn->nBufferSize);
                    if (portDefn->nBufferCountActual > MAX_NUM_OUTPUT_BUFFERS) {
                        DEBUG_PRINT_ERROR("ERROR: (Out_PORT) actual count (%u) exceeds max(%u)",
                                (unsigned int)portDefn->nBufferCountActual, (unsigned int)MAX_NUM_OUTPUT_BUFFERS);
                        return OMX_ErrorUnsupportedSetting;
                    }
                     if (portDefn->nBufferCountMin > portDefn->nBufferCountActual) {
                         DEBUG_PRINT_ERROR("ERROR: (Out_PORT) Min buffers (%u) > actual count (%u)",
                                 (unsigned int)portDefn->nBufferCountMin, (unsigned int)portDefn->nBufferCountActual);
 return OMX_ErrorUnsupportedSetting;
 }
 if (handle->venc_set_param(paramData,OMX_IndexParamPortDefinition) != true) {
                        DEBUG_PRINT_ERROR("ERROR: venc_set_param output failed");
 return OMX_ErrorUnsupportedSetting;
 }
#ifdef _MSM8974_
 /*Query ouput Buffer Requirements*/
                    dev_get_buf_req(&m_sOutPortDef.nBufferCountMin,
 &m_sOutPortDef.nBufferCountActual,
 &m_sOutPortDef.nBufferSize,
                            m_sOutPortDef.nPortIndex);
#endif
                    memcpy(&m_sOutPortDef,portDefn,sizeof(struct OMX_PARAM_PORTDEFINITIONTYPE));
                    update_profile_level(); //framerate , bitrate

                    DEBUG_PRINT_LOW("o/p previous actual cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountActual);
                    DEBUG_PRINT_LOW("o/p previous min cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountMin);
                    m_sOutPortDef.nBufferCountActual = portDefn->nBufferCountActual;
 } else {
                    DEBUG_PRINT_ERROR("ERROR: Set_parameter: Bad Port idx %d",
 (int)portDefn->nPortIndex);
                    eRet = OMX_ErrorBadPortIndex;
 }
                m_sConfigFramerate.xEncodeFramerate = portDefn->format.video.xFramerate;
                m_sConfigBitrate.nEncodeBitrate = portDefn->format.video.nBitrate;
                m_sParamBitrate.nTargetBitrate = portDefn->format.video.nBitrate;
 }
 break;

 case OMX_IndexParamVideoPortFormat:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PORTFORMATTYPE);
                OMX_VIDEO_PARAM_PORTFORMATTYPE *portFmt =
 (OMX_VIDEO_PARAM_PORTFORMATTYPE *)paramData;
                DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoPortFormat %d",
                        portFmt->eColorFormat);
 if (PORT_INDEX_IN == portFmt->nPortIndex) {
 if (handle->venc_set_param(paramData,OMX_IndexParamVideoPortFormat) != true) {
 return OMX_ErrorUnsupportedSetting;
 }

                    DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoPortFormat %d",
                            portFmt->eColorFormat);
                    update_profile_level(); //framerate

#ifdef _ANDROID_ICS_
 if (portFmt->eColorFormat ==
 (OMX_COLOR_FORMATTYPE)QOMX_COLOR_FormatAndroidOpaque) {
                        m_sInPortFormat.eColorFormat = (OMX_COLOR_FORMATTYPE)
                            QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m;
 if (!mUseProxyColorFormat) {
 if (!c2d_conv.init()) {
                                DEBUG_PRINT_ERROR("C2D init failed");
 return OMX_ErrorUnsupportedSetting;
 }
                            DEBUG_PRINT_HIGH("C2D init is successful");
 }
                        mUseProxyColorFormat = true;
                        m_input_msg_id = OMX_COMPONENT_GENERATE_ETB_OPQ;
 } else
#endif
 {
                        m_sInPortFormat.eColorFormat = portFmt->eColorFormat;
                        m_sInPortDef.format.video.eColorFormat = portFmt->eColorFormat;
                        m_input_msg_id = OMX_COMPONENT_GENERATE_ETB;
                        mUseProxyColorFormat = false;
 }
                    m_sInPortFormat.xFramerate = portFmt->xFramerate;
 }
 }
 break;
 case OMX_IndexParamVideoInit:
 { //TODO, do we need this index set param
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_PORT_PARAM_TYPE);
                OMX_PORT_PARAM_TYPE* pParam = (OMX_PORT_PARAM_TYPE*)(paramData);
                DEBUG_PRINT_LOW("Set OMX_IndexParamVideoInit called");
 break;
 }

 case OMX_IndexParamVideoBitrate:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_BITRATETYPE);
                OMX_VIDEO_PARAM_BITRATETYPE* pParam = (OMX_VIDEO_PARAM_BITRATETYPE*)paramData;
                DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoBitrate");
 if (handle->venc_set_param(paramData,OMX_IndexParamVideoBitrate) != true) {
 return OMX_ErrorUnsupportedSetting;
 }
                m_sParamBitrate.nTargetBitrate = pParam->nTargetBitrate;
                m_sParamBitrate.eControlRate = pParam->eControlRate;
                update_profile_level(); //bitrate
                m_sConfigBitrate.nEncodeBitrate = pParam->nTargetBitrate;
                m_sInPortDef.format.video.nBitrate = pParam->nTargetBitrate;
                m_sOutPortDef.format.video.nBitrate = pParam->nTargetBitrate;
                DEBUG_PRINT_LOW("bitrate = %u", (unsigned int)m_sOutPortDef.format.video.nBitrate);
 break;
 }
 case OMX_IndexParamVideoMpeg4:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_MPEG4TYPE);
                OMX_VIDEO_PARAM_MPEG4TYPE* pParam = (OMX_VIDEO_PARAM_MPEG4TYPE*)paramData;
                OMX_VIDEO_PARAM_MPEG4TYPE mp4_param;
                memcpy(&mp4_param, pParam, sizeof(struct OMX_VIDEO_PARAM_MPEG4TYPE));
                DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoMpeg4");
 if (pParam->eProfile == OMX_VIDEO_MPEG4ProfileAdvancedSimple) {
#ifdef MAX_RES_1080P
 if (pParam->nBFrames) {
                        DEBUG_PRINT_HIGH("INFO: Only 1 Bframe is supported");
                        mp4_param.nBFrames = 1;
 }
#else
 if (pParam->nBFrames) {
                        DEBUG_PRINT_ERROR("Warning: B frames not supported");
                        mp4_param.nBFrames = 0;
 }
#endif
#ifdef _MSM8974_
 if (pParam->nBFrames || bframes)
                        mp4_param.nBFrames = (pParam->nBFrames > (unsigned int) bframes)? pParam->nBFrames : bframes;
                    DEBUG_PRINT_HIGH("MPEG4: %u BFrames are being set", (unsigned int)mp4_param.nBFrames);
#endif

 } else {
 if (pParam->nBFrames) {
                        DEBUG_PRINT_ERROR("Warning: B frames not supported");
                        mp4_param.nBFrames = 0;
 }
 }
 if (handle->venc_set_param(&mp4_param,OMX_IndexParamVideoMpeg4) != true) {
 return OMX_ErrorUnsupportedSetting;
 }
                memcpy(&m_sParamMPEG4,pParam, sizeof(struct OMX_VIDEO_PARAM_MPEG4TYPE));
                m_sIntraperiod.nPFrames = m_sParamMPEG4.nPFrames;
 if (pParam->nBFrames || bframes)
                    m_sIntraperiod.nBFrames = m_sParamMPEG4.nBFrames = mp4_param.nBFrames;
 else
                m_sIntraperiod.nBFrames = m_sParamMPEG4.nBFrames;
 break;
 }
 case OMX_IndexParamVideoH263:
 {
                OMX_VIDEO_PARAM_H263TYPE* pParam = (OMX_VIDEO_PARAM_H263TYPE*)paramData;
                DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoH263");
 if (handle->venc_set_param(paramData,OMX_IndexParamVideoH263) != true) {
 return OMX_ErrorUnsupportedSetting;
 }
                memcpy(&m_sParamH263,pParam, sizeof(struct OMX_VIDEO_PARAM_H263TYPE));
                m_sIntraperiod.nPFrames = m_sParamH263.nPFrames;
                m_sIntraperiod.nBFrames = m_sParamH263.nBFrames;
 break;
 }
 case OMX_IndexParamVideoAvc:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_AVCTYPE);
                OMX_VIDEO_PARAM_AVCTYPE* pParam = (OMX_VIDEO_PARAM_AVCTYPE*)paramData;
                OMX_VIDEO_PARAM_AVCTYPE avc_param;
                memcpy(&avc_param, pParam, sizeof( struct OMX_VIDEO_PARAM_AVCTYPE));
                DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoAvc");

 if ((pParam->eProfile == OMX_VIDEO_AVCProfileHigh)||
 (pParam->eProfile == OMX_VIDEO_AVCProfileMain)) {
#ifdef MAX_RES_1080P
 if (pParam->nBFrames) {
                        DEBUG_PRINT_HIGH("INFO: Only 1 Bframe is supported");
                        avc_param.nBFrames = 1;
 }
 if (pParam->nRefFrames != 2) {
                        DEBUG_PRINT_ERROR("Warning: 2 RefFrames are needed, changing RefFrames from %u to 2", (unsigned int)pParam->nRefFrames);
                        avc_param.nRefFrames = 2;
 }
#else
 if (pParam->nBFrames) {
                        DEBUG_PRINT_ERROR("Warning: B frames not supported");
                        avc_param.nBFrames = 0;
 }
 if (pParam->nRefFrames != 1) {
                        DEBUG_PRINT_ERROR("Warning: Only 1 RefFrame is supported, changing RefFrame from %u to 1)", (unsigned int)pParam->nRefFrames);
                        avc_param.nRefFrames = 1;
 }
#endif
#ifdef _MSM8974_
 if (pParam->nBFrames || bframes) {
                        avc_param.nBFrames = (pParam->nBFrames > (unsigned int) bframes)? pParam->nBFrames : bframes;
                        avc_param.nRefFrames = (avc_param.nBFrames < 4)? avc_param.nBFrames + 1 : 4;
 }
                    DEBUG_PRINT_HIGH("AVC: RefFrames: %u, BFrames: %u", (unsigned int)avc_param.nRefFrames, (unsigned int)avc_param.nBFrames);

                    avc_param.bEntropyCodingCABAC = (OMX_BOOL)(avc_param.bEntropyCodingCABAC && entropy);
                    avc_param.nCabacInitIdc = entropy ? avc_param.nCabacInitIdc : 0;
#endif
 } else {
 if (pParam->nRefFrames != 1) {
                        DEBUG_PRINT_ERROR("Warning: Only 1 RefFrame is supported, changing RefFrame from %u to 1)", (unsigned int)pParam->nRefFrames);
                        avc_param.nRefFrames = 1;
 }
 if (pParam->nBFrames) {
                        DEBUG_PRINT_ERROR("Warning: B frames not supported");
                        avc_param.nBFrames = 0;
 }
 }
 if (handle->venc_set_param(&avc_param,OMX_IndexParamVideoAvc) != true) {
 return OMX_ErrorUnsupportedSetting;
 }
                memcpy(&m_sParamAVC,pParam, sizeof(struct OMX_VIDEO_PARAM_AVCTYPE));
                m_sIntraperiod.nPFrames = m_sParamAVC.nPFrames;
 if (pParam->nBFrames || bframes)
                    m_sIntraperiod.nBFrames = m_sParamAVC.nBFrames = avc_param.nBFrames;
 else
                m_sIntraperiod.nBFrames = m_sParamAVC.nBFrames;
 break;
 }
 case (OMX_INDEXTYPE)OMX_IndexParamVideoVp8:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_VP8TYPE);
                OMX_VIDEO_PARAM_VP8TYPE* pParam = (OMX_VIDEO_PARAM_VP8TYPE*)paramData;
                OMX_VIDEO_PARAM_VP8TYPE vp8_param;
                DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoVp8");
 if (pParam->nDCTPartitions != m_sParamVP8.nDCTPartitions ||
                    pParam->bErrorResilientMode != m_sParamVP8.bErrorResilientMode) {
                    DEBUG_PRINT_ERROR("VP8 doesn't support nDCTPartitions or bErrorResilientMode");
 }
                memcpy(&vp8_param, pParam, sizeof( struct OMX_VIDEO_PARAM_VP8TYPE));
 if (handle->venc_set_param(&vp8_param, (OMX_INDEXTYPE)OMX_IndexParamVideoVp8) != true) {
 return OMX_ErrorUnsupportedSetting;
 }
                memcpy(&m_sParamVP8,pParam, sizeof(struct OMX_VIDEO_PARAM_VP8TYPE));
 break;
 }
 case (OMX_INDEXTYPE)OMX_IndexParamVideoHevc:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_HEVCTYPE);
                OMX_VIDEO_PARAM_HEVCTYPE* pParam = (OMX_VIDEO_PARAM_HEVCTYPE*)paramData;
                OMX_VIDEO_PARAM_HEVCTYPE hevc_param;
                DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoHevc");
                memcpy(&hevc_param, pParam, sizeof( struct OMX_VIDEO_PARAM_HEVCTYPE));
 if (handle->venc_set_param(&hevc_param, (OMX_INDEXTYPE)OMX_IndexParamVideoHevc) != true) {
                    DEBUG_PRINT_ERROR("Failed : set_parameter: OMX_IndexParamVideoHevc");
 return OMX_ErrorUnsupportedSetting;
 }
                memcpy(&m_sParamHEVC, pParam, sizeof(struct OMX_VIDEO_PARAM_HEVCTYPE));
 break;
 }
 case OMX_IndexParamVideoProfileLevelCurrent:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PROFILELEVELTYPE);
                OMX_VIDEO_PARAM_PROFILELEVELTYPE* pParam = (OMX_VIDEO_PARAM_PROFILELEVELTYPE*)paramData;
                DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoProfileLevelCurrent");
 if (handle->venc_set_param(pParam,OMX_IndexParamVideoProfileLevelCurrent) != true) {
                    DEBUG_PRINT_ERROR("set_parameter: OMX_IndexParamVideoProfileLevelCurrent failed for Profile: %u "
 "Level :%u", (unsigned int)pParam->eProfile, (unsigned int)pParam->eLevel);
 return OMX_ErrorUnsupportedSetting;
 }
                m_sParamProfileLevel.eProfile = pParam->eProfile;
                m_sParamProfileLevel.eLevel = pParam->eLevel;

 if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.mpeg4",\
                            OMX_MAX_STRINGNAME_SIZE)) {
                    m_sParamMPEG4.eProfile = (OMX_VIDEO_MPEG4PROFILETYPE)m_sParamProfileLevel.eProfile;
                    m_sParamMPEG4.eLevel = (OMX_VIDEO_MPEG4LEVELTYPE)m_sParamProfileLevel.eLevel;
                    DEBUG_PRINT_LOW("MPEG4 profile = %d, level = %d", m_sParamMPEG4.eProfile,
                            m_sParamMPEG4.eLevel);
 } else if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.h263",\
                            OMX_MAX_STRINGNAME_SIZE)) {
                    m_sParamH263.eProfile = (OMX_VIDEO_H263PROFILETYPE)m_sParamProfileLevel.eProfile;
                    m_sParamH263.eLevel = (OMX_VIDEO_H263LEVELTYPE)m_sParamProfileLevel.eLevel;
                    DEBUG_PRINT_LOW("H263 profile = %d, level = %d", m_sParamH263.eProfile,
                            m_sParamH263.eLevel);
 } else if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.avc",\
                            OMX_MAX_STRINGNAME_SIZE)) {
                    m_sParamAVC.eProfile = (OMX_VIDEO_AVCPROFILETYPE)m_sParamProfileLevel.eProfile;
                    m_sParamAVC.eLevel = (OMX_VIDEO_AVCLEVELTYPE)m_sParamProfileLevel.eLevel;
                    DEBUG_PRINT_LOW("AVC profile = %d, level = %d", m_sParamAVC.eProfile,
                            m_sParamAVC.eLevel);
 } else if (!strncmp((char *)m_nkind, "OMX.qcom.video.encoder.avc.secure",\
                            OMX_MAX_STRINGNAME_SIZE)) {
                    m_sParamAVC.eProfile = (OMX_VIDEO_AVCPROFILETYPE)m_sParamProfileLevel.eProfile;
                    m_sParamAVC.eLevel = (OMX_VIDEO_AVCLEVELTYPE)m_sParamProfileLevel.eLevel;
                    DEBUG_PRINT_LOW("\n AVC profile = %d, level = %d", m_sParamAVC.eProfile,
                            m_sParamAVC.eLevel);
 }
 else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.vp8",\
                            OMX_MAX_STRINGNAME_SIZE)) {
                    m_sParamVP8.eProfile = (OMX_VIDEO_VP8PROFILETYPE)m_sParamProfileLevel.eProfile;
                    m_sParamVP8.eLevel = (OMX_VIDEO_VP8LEVELTYPE)m_sParamProfileLevel.eLevel;
                    DEBUG_PRINT_LOW("VP8 profile = %d, level = %d", m_sParamVP8.eProfile,
                            m_sParamVP8.eLevel);
 }
 else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.hevc",\
                            OMX_MAX_STRINGNAME_SIZE)) {
                    m_sParamHEVC.eProfile = (OMX_VIDEO_HEVCPROFILETYPE)m_sParamProfileLevel.eProfile;
                    m_sParamHEVC.eLevel = (OMX_VIDEO_HEVCLEVELTYPE)m_sParamProfileLevel.eLevel;
                    DEBUG_PRINT_LOW("HEVC profile = %d, level = %d", m_sParamHEVC.eProfile,
                            m_sParamHEVC.eLevel);
 }

 break;
 }
 case OMX_IndexParamStandardComponentRole:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_COMPONENTROLETYPE);
                OMX_PARAM_COMPONENTROLETYPE *comp_role;
                comp_role = (OMX_PARAM_COMPONENTROLETYPE *) paramData;
                DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamStandardComponentRole %s",
                        comp_role->cRole);

 if ((m_state == OMX_StateLoaded)&&
 !BITMASK_PRESENT(&m_flags,OMX_COMPONENT_IDLE_PENDING)) {
                    DEBUG_PRINT_LOW("Set Parameter called in valid state");
 } else {
                    DEBUG_PRINT_ERROR("Set Parameter called in Invalid State");
 return OMX_ErrorIncorrectStateOperation;
 }

 if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.avc",OMX_MAX_STRINGNAME_SIZE)) {
 if (!strncmp((char*)comp_role->cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE)) {
                        strlcpy((char*)m_cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE);
 } else {
                        DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole);
                        eRet =OMX_ErrorUnsupportedSetting;
 }
 } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.avc.secure",OMX_MAX_STRINGNAME_SIZE)) {
 if (!strncmp((char*)comp_role->cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE)) {
                        strlcpy((char*)m_cRole,"video_encoder.avc",OMX_MAX_STRINGNAME_SIZE);
 } else {
                        DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s\n", comp_role->cRole);
                        eRet =OMX_ErrorUnsupportedSetting;
 }
 } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) {
 if (!strncmp((const char*)comp_role->cRole,"video_encoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) {
                        strlcpy((char*)m_cRole,"video_encoder.mpeg4",OMX_MAX_STRINGNAME_SIZE);
 } else {
                        DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole);
                        eRet = OMX_ErrorUnsupportedSetting;
 }
 } else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.h263",OMX_MAX_STRINGNAME_SIZE)) {
 if (!strncmp((const char*)comp_role->cRole,"video_encoder.h263",OMX_MAX_STRINGNAME_SIZE)) {
                        strlcpy((char*)m_cRole,"video_encoder.h263",OMX_MAX_STRINGNAME_SIZE);
 } else {
                        DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole);
                        eRet =OMX_ErrorUnsupportedSetting;
 }
 }
#ifdef _MSM8974_
 else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.vp8",OMX_MAX_STRINGNAME_SIZE)) {
 if (!strncmp((const char*)comp_role->cRole,"video_encoder.vp8",OMX_MAX_STRINGNAME_SIZE)) {
                        strlcpy((char*)m_cRole,"video_encoder.vp8",OMX_MAX_STRINGNAME_SIZE);
 } else {
                        DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole);
                        eRet =OMX_ErrorUnsupportedSetting;
 }
 }
#endif
 else if (!strncmp((char*)m_nkind, "OMX.qcom.video.encoder.hevc",OMX_MAX_STRINGNAME_SIZE)) {
 if (!strncmp((const char*)comp_role->cRole,"video_encoder.hevc",OMX_MAX_STRINGNAME_SIZE)) {
                        strlcpy((char*)m_cRole,"video_encoder.hevc",OMX_MAX_STRINGNAME_SIZE);
 } else {
                        DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown Index %s", comp_role->cRole);
                        eRet = OMX_ErrorUnsupportedSetting;
 }
 }

 else {
                    DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown param %s", m_nkind);
                    eRet = OMX_ErrorInvalidComponentName;
 }
 break;
 }

 case OMX_IndexParamPriorityMgmt:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_PRIORITYMGMTTYPE);
                DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPriorityMgmt");
 if (m_state != OMX_StateLoaded) {
                    DEBUG_PRINT_ERROR("ERROR: Set Parameter called in Invalid State");
 return OMX_ErrorIncorrectStateOperation;
 }
                OMX_PRIORITYMGMTTYPE *priorityMgmtype = (OMX_PRIORITYMGMTTYPE*) paramData;
                DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPriorityMgmt %u",
 (unsigned int)priorityMgmtype->nGroupID);

                DEBUG_PRINT_LOW("set_parameter: priorityMgmtype %u",
 (unsigned int)priorityMgmtype->nGroupPriority);

                m_sPriorityMgmt.nGroupID = priorityMgmtype->nGroupID;
                m_sPriorityMgmt.nGroupPriority = priorityMgmtype->nGroupPriority;

 break;
 }

 case OMX_IndexParamCompBufferSupplier:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_BUFFERSUPPLIERTYPE);
                DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamCompBufferSupplier");
                OMX_PARAM_BUFFERSUPPLIERTYPE *bufferSupplierType = (OMX_PARAM_BUFFERSUPPLIERTYPE*) paramData;
                DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamCompBufferSupplier %d",
                        bufferSupplierType->eBufferSupplier);
 if (bufferSupplierType->nPortIndex == 0 || bufferSupplierType->nPortIndex ==1)
                    m_sInBufSupplier.eBufferSupplier = bufferSupplierType->eBufferSupplier;

 else

                    eRet = OMX_ErrorBadPortIndex;

 break;

 }
 case OMX_IndexParamVideoQuantization:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_QUANTIZATIONTYPE);
                DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoQuantization");
                OMX_VIDEO_PARAM_QUANTIZATIONTYPE *session_qp = (OMX_VIDEO_PARAM_QUANTIZATIONTYPE*) paramData;
 if (session_qp->nPortIndex == PORT_INDEX_OUT) {
 if (handle->venc_set_param(paramData, OMX_IndexParamVideoQuantization) != true) {
 return OMX_ErrorUnsupportedSetting;
 }
                    m_sSessionQuantization.nQpI = session_qp->nQpI;
                    m_sSessionQuantization.nQpP = session_qp->nQpP;
                    m_sSessionQuantization.nQpB = session_qp->nQpB;
 } else {
                    DEBUG_PRINT_ERROR("ERROR: Unsupported port Index for Session QP setting");
                    eRet = OMX_ErrorBadPortIndex;
 }
 break;
 }

 case OMX_QcomIndexParamVideoQPRange:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_VIDEO_PARAM_QPRANGETYPE);
                DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexParamVideoQPRange");
                OMX_QCOM_VIDEO_PARAM_QPRANGETYPE *qp_range = (OMX_QCOM_VIDEO_PARAM_QPRANGETYPE*) paramData;
 if (qp_range->nPortIndex == PORT_INDEX_OUT) {
 if (handle->venc_set_param(paramData,
 (OMX_INDEXTYPE)OMX_QcomIndexParamVideoQPRange) != true) {
 return OMX_ErrorUnsupportedSetting;
 }
                    m_sSessionQPRange.minQP= qp_range->minQP;
                    m_sSessionQPRange.maxQP= qp_range->maxQP;
 } else {
                    DEBUG_PRINT_ERROR("ERROR: Unsupported port Index for QP range setting");
                    eRet = OMX_ErrorBadPortIndex;
 }
 break;
 }

 case OMX_QcomIndexPortDefn:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_PARAM_PORTDEFINITIONTYPE);
                OMX_QCOM_PARAM_PORTDEFINITIONTYPE* pParam =
 (OMX_QCOM_PARAM_PORTDEFINITIONTYPE*)paramData;
                DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexPortDefn");
 if (pParam->nPortIndex == (OMX_U32)PORT_INDEX_IN) {
 if (pParam->nMemRegion > OMX_QCOM_MemRegionInvalid &&
                            pParam->nMemRegion < OMX_QCOM_MemRegionMax) {
                        m_use_input_pmem = OMX_TRUE;
 } else {
                        m_use_input_pmem = OMX_FALSE;
 }
 } else if (pParam->nPortIndex == (OMX_U32)PORT_INDEX_OUT) {
 if (pParam->nMemRegion > OMX_QCOM_MemRegionInvalid &&
                            pParam->nMemRegion < OMX_QCOM_MemRegionMax) {
                        m_use_output_pmem = OMX_TRUE;
 } else {
                        m_use_output_pmem = OMX_FALSE;
 }
 } else {
                    DEBUG_PRINT_ERROR("ERROR: SetParameter called on unsupported Port Index for QcomPortDefn");
 return OMX_ErrorBadPortIndex;
 }
 break;
 }

 case OMX_IndexParamVideoErrorCorrection:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE);
                DEBUG_PRINT_LOW("OMX_IndexParamVideoErrorCorrection");
                OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE* pParam =
 (OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE*)paramData;
 if (!handle->venc_set_param(paramData, OMX_IndexParamVideoErrorCorrection)) {
                    DEBUG_PRINT_ERROR("ERROR: Request for setting Error Resilience failed");
 return OMX_ErrorUnsupportedSetting;
 }
                memcpy(&m_sErrorCorrection,pParam, sizeof(m_sErrorCorrection));
 break;
 }
 case OMX_IndexParamVideoIntraRefresh:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_INTRAREFRESHTYPE);
                DEBUG_PRINT_LOW("set_param:OMX_IndexParamVideoIntraRefresh");
                OMX_VIDEO_PARAM_INTRAREFRESHTYPE* pParam =
 (OMX_VIDEO_PARAM_INTRAREFRESHTYPE*)paramData;
 if (!handle->venc_set_param(paramData,OMX_IndexParamVideoIntraRefresh)) {
                    DEBUG_PRINT_ERROR("ERROR: Request for setting intra refresh failed");
 return OMX_ErrorUnsupportedSetting;
 }
                memcpy(&m_sIntraRefresh, pParam, sizeof(m_sIntraRefresh));
 break;
 }
#ifdef _ANDROID_ICS_
 case OMX_QcomIndexParamVideoMetaBufferMode:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, StoreMetaDataInBuffersParams);
 StoreMetaDataInBuffersParams *pParam =
 (StoreMetaDataInBuffersParams*)paramData;
                DEBUG_PRINT_HIGH("set_parameter:OMX_QcomIndexParamVideoMetaBufferMode: "
 "port_index = %u, meta_mode = %d", (unsigned int)pParam->nPortIndex, pParam->bStoreMetaData);
 if (pParam->nPortIndex == PORT_INDEX_IN) {
 if (pParam->bStoreMetaData != meta_mode_enable) {
 if (!handle->venc_set_meta_mode(pParam->bStoreMetaData)) {
                            DEBUG_PRINT_ERROR("ERROR: set Metabuffer mode %d fail",
                                    pParam->bStoreMetaData);
 return OMX_ErrorUnsupportedSetting;
 }
                        meta_mode_enable = pParam->bStoreMetaData;
 if (meta_mode_enable) {
                            m_sInPortDef.nBufferCountActual = m_sInPortDef.nBufferCountMin;
 if (handle->venc_set_param(&m_sInPortDef,OMX_IndexParamPortDefinition) != true) {
                                DEBUG_PRINT_ERROR("ERROR: venc_set_param input failed");
 return OMX_ErrorUnsupportedSetting;
 }
 } else {
 /*TODO: reset encoder driver Meta mode*/
                            dev_get_buf_req   (&m_sOutPortDef.nBufferCountMin,
 &m_sOutPortDef.nBufferCountActual,
 &m_sOutPortDef.nBufferSize,
                                    m_sOutPortDef.nPortIndex);
 }
 }
 } else if (pParam->nPortIndex == PORT_INDEX_OUT && secure_session) {
 if (pParam->bStoreMetaData != meta_mode_enable) {
 if (!handle->venc_set_meta_mode(pParam->bStoreMetaData)) {
                            DEBUG_PRINT_ERROR("\nERROR: set Metabuffer mode %d fail",
                                    pParam->bStoreMetaData);
 return OMX_ErrorUnsupportedSetting;
 }
                        meta_mode_enable = pParam->bStoreMetaData;
 }
 } else {
                    DEBUG_PRINT_ERROR("set_parameter: metamode is "
 "valid for input port only");
                    eRet = OMX_ErrorUnsupportedIndex;
 }
 }
 break;
#endif
#if !defined(MAX_RES_720P) || defined(_MSM8974_)
 case OMX_QcomIndexParamIndexExtraDataType:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXEXTRADATATYPE);
                DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamIndexExtraDataType");
                QOMX_INDEXEXTRADATATYPE *pParam = (QOMX_INDEXEXTRADATATYPE *)paramData;
 bool enable = false;
                OMX_U32 mask = 0;

 if (pParam->nIndex == (OMX_INDEXTYPE)OMX_ExtraDataVideoEncoderSliceInfo) {
 if (pParam->nPortIndex == PORT_INDEX_OUT) {
                        mask = VEN_EXTRADATA_SLICEINFO;

                        DEBUG_PRINT_HIGH("SliceInfo extradata %s",
 ((pParam->bEnabled == OMX_TRUE) ? "enabled" : "disabled"));
 } else {
                        DEBUG_PRINT_ERROR("set_parameter: Slice information is "
 "valid for output port only");
                        eRet = OMX_ErrorUnsupportedIndex;
 break;
 }
 } else if (pParam->nIndex == (OMX_INDEXTYPE)OMX_ExtraDataVideoEncoderMBInfo) {
 if (pParam->nPortIndex == PORT_INDEX_OUT) {
                        mask = VEN_EXTRADATA_MBINFO;

                        DEBUG_PRINT_HIGH("MBInfo extradata %s",
 ((pParam->bEnabled == OMX_TRUE) ? "enabled" : "disabled"));
 } else {
                        DEBUG_PRINT_ERROR("set_parameter: MB information is "
 "valid for output port only");
                        eRet = OMX_ErrorUnsupportedIndex;
 break;
 }
 }
#ifndef _MSM8974_
 else if (pParam->nIndex == (OMX_INDEXTYPE)OMX_ExtraDataVideoLTRInfo) {
 if (pParam->nPortIndex == PORT_INDEX_OUT) {
 if (pParam->bEnabled == OMX_TRUE)
                            mask = VEN_EXTRADATA_LTRINFO;

                        DEBUG_PRINT_HIGH("LTRInfo extradata %s",
 ((pParam->bEnabled == OMX_TRUE) ? "enabled" : "disabled"));
 } else {
                        DEBUG_PRINT_ERROR("set_parameter: LTR information is "
 "valid for output port only");
                        eRet = OMX_ErrorUnsupportedIndex;
 break;
 }
 }
#endif
 else {
                    DEBUG_PRINT_ERROR("set_parameter: unsupported extrdata index (%x)",
                            pParam->nIndex);
                    eRet = OMX_ErrorUnsupportedIndex;
 break;
 }

 if (pParam->bEnabled == OMX_TRUE)
                    m_sExtraData |= mask;
 else
                    m_sExtraData &= ~mask;

                enable = !!(m_sExtraData & mask);
 if (handle->venc_set_param(&enable,
 (OMX_INDEXTYPE)pParam->nIndex) != true) {
                    DEBUG_PRINT_ERROR("ERROR: Setting Extradata (%x) failed", pParam->nIndex);
 return OMX_ErrorUnsupportedSetting;
 } else {
                    m_sOutPortDef.nPortIndex = PORT_INDEX_OUT;
                    dev_get_buf_req(&m_sOutPortDef.nBufferCountMin,
 &m_sOutPortDef.nBufferCountActual,
 &m_sOutPortDef.nBufferSize,
                            m_sOutPortDef.nPortIndex);
                    DEBUG_PRINT_HIGH("updated out_buf_req: buffer cnt=%u, "
 "count min=%u, buffer size=%u",
 (unsigned int)m_sOutPortDef.nBufferCountActual,
 (unsigned int)m_sOutPortDef.nBufferCountMin,
 (unsigned int)m_sOutPortDef.nBufferSize);
 }
 break;
 }
 case QOMX_IndexParamVideoLTRMode:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_PARAM_LTRMODE_TYPE);
                QOMX_VIDEO_PARAM_LTRMODE_TYPE* pParam =
 (QOMX_VIDEO_PARAM_LTRMODE_TYPE*)paramData;
 if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)QOMX_IndexParamVideoLTRMode)) {
                    DEBUG_PRINT_ERROR("ERROR: Setting LTR mode failed");
 return OMX_ErrorUnsupportedSetting;
 }
                memcpy(&m_sParamLTRMode, pParam, sizeof(m_sParamLTRMode));
 break;
 }
 case QOMX_IndexParamVideoLTRCount:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_PARAM_LTRCOUNT_TYPE);
                QOMX_VIDEO_PARAM_LTRCOUNT_TYPE* pParam =
 (QOMX_VIDEO_PARAM_LTRCOUNT_TYPE*)paramData;
 if (!handle->venc_set_param(paramData, (OMX_INDEXTYPE)QOMX_IndexParamVideoLTRCount)) {
                    DEBUG_PRINT_ERROR("ERROR: Setting LTR count failed");
 return OMX_ErrorUnsupportedSetting;
 }
                memcpy(&m_sParamLTRCount, pParam, sizeof(m_sParamLTRCount));
 break;
 }
#endif
 case OMX_QcomIndexParamVideoMaxAllowedBitrateCheck:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, QOMX_EXTNINDEX_PARAMTYPE);
                QOMX_EXTNINDEX_PARAMTYPE* pParam =
 (QOMX_EXTNINDEX_PARAMTYPE*)paramData;
 if (pParam->nPortIndex == PORT_INDEX_OUT) {
                    handle->m_max_allowed_bitrate_check =
 ((pParam->bEnable == OMX_TRUE) ? true : false);
                    DEBUG_PRINT_HIGH("set_parameter: max allowed bitrate check %s",
 ((pParam->bEnable == OMX_TRUE) ? "enabled" : "disabled"));
 } else {
                    DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexParamVideoMaxAllowedBitrateCheck "
 " called on wrong port(%u)", (unsigned int)pParam->nPortIndex);
 return OMX_ErrorBadPortIndex;
 }
 break;
 }
#ifdef MAX_RES_1080P
 case OMX_QcomIndexEnableSliceDeliveryMode:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, QOMX_EXTNINDEX_PARAMTYPE);
                QOMX_EXTNINDEX_PARAMTYPE* pParam =
 (QOMX_EXTNINDEX_PARAMTYPE*)paramData;
 if (pParam->nPortIndex == PORT_INDEX_OUT) {
 if (!handle->venc_set_param(paramData,
 (OMX_INDEXTYPE)OMX_QcomIndexEnableSliceDeliveryMode)) {
                        DEBUG_PRINT_ERROR("ERROR: Request for setting slice delivery mode failed");
 return OMX_ErrorUnsupportedSetting;
 }
 } else {
                    DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexEnableSliceDeliveryMode "
 "called on wrong port(%u)", (unsigned int)pParam->nPortIndex);
 return OMX_ErrorBadPortIndex;
 }
 break;
 }
#endif
 case OMX_QcomIndexEnableH263PlusPType:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, QOMX_EXTNINDEX_PARAMTYPE);
                QOMX_EXTNINDEX_PARAMTYPE* pParam =
 (QOMX_EXTNINDEX_PARAMTYPE*)paramData;
                DEBUG_PRINT_LOW("OMX_QcomIndexEnableH263PlusPType");
 if (pParam->nPortIndex == PORT_INDEX_OUT) {
 if (!handle->venc_set_param(paramData,
 (OMX_INDEXTYPE)OMX_QcomIndexEnableH263PlusPType)) {
                        DEBUG_PRINT_ERROR("ERROR: Request for setting PlusPType failed");
 return OMX_ErrorUnsupportedSetting;
 }
 } else {
                    DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexEnableH263PlusPType "
 "called on wrong port(%u)", (unsigned int)pParam->nPortIndex);
 return OMX_ErrorBadPortIndex;
 }
 break;
 }
 case OMX_QcomIndexParamSequenceHeaderWithIDR:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, PrependSPSPPSToIDRFramesParams);
 if(!handle->venc_set_param(paramData,
 (OMX_INDEXTYPE)OMX_QcomIndexParamSequenceHeaderWithIDR)) {
                    DEBUG_PRINT_ERROR("%s: %s",
 "OMX_QComIndexParamSequenceHeaderWithIDR:",
 "request for inband sps/pps failed.");
 return OMX_ErrorUnsupportedSetting;
 }
 break;
 }
 case OMX_QcomIndexParamH264AUDelimiter:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_VIDEO_CONFIG_H264_AUD);
 if(!handle->venc_set_param(paramData,
 (OMX_INDEXTYPE)OMX_QcomIndexParamH264AUDelimiter)) {
                    DEBUG_PRINT_ERROR("%s: %s",
 "OMX_QComIndexParamh264AUDelimiter:",
 "request for AU Delimiters failed.");
 return OMX_ErrorUnsupportedSetting;
 }
 break;
 }
 case OMX_QcomIndexHierarchicalStructure:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_HIERARCHICALLAYERS);
                QOMX_VIDEO_HIERARCHICALLAYERS* pParam =
 (QOMX_VIDEO_HIERARCHICALLAYERS*)paramData;
                DEBUG_PRINT_LOW("OMX_QcomIndexHierarchicalStructure");
 if (pParam->nPortIndex == PORT_INDEX_OUT) {
 if (!handle->venc_set_param(paramData,
 (OMX_INDEXTYPE)OMX_QcomIndexHierarchicalStructure)) {
                        DEBUG_PRINT_ERROR("ERROR: Request for setting PlusPType failed");
 return OMX_ErrorUnsupportedSetting;
 }
 if((pParam->eHierarchicalCodingType == QOMX_HIERARCHICALCODING_B) && pParam->nNumLayers)
                    hier_b_enabled = true;
                    m_sHierLayers.nNumLayers = pParam->nNumLayers;
                    m_sHierLayers.eHierarchicalCodingType = pParam->eHierarchicalCodingType;
 } else {
                    DEBUG_PRINT_ERROR("ERROR: OMX_QcomIndexHierarchicalStructure called on wrong port(%u)",
 (unsigned int)pParam->nPortIndex);
 return OMX_ErrorBadPortIndex;
 }
 break;

 }
 case OMX_QcomIndexParamPerfLevel:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_VIDEO_PARAM_PERF_LEVEL);
 if (!handle->venc_set_param(paramData,
 (OMX_INDEXTYPE) OMX_QcomIndexParamPerfLevel)) {
                    DEBUG_PRINT_ERROR("ERROR: Setting performance level");
 return OMX_ErrorUnsupportedSetting;
 }
 break;
 }
 case OMX_QcomIndexParamH264VUITimingInfo:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_VIDEO_PARAM_VUI_TIMING_INFO);
 if (!handle->venc_set_param(paramData,
 (OMX_INDEXTYPE) OMX_QcomIndexParamH264VUITimingInfo)) {
                    DEBUG_PRINT_ERROR("ERROR: Setting VUI timing info");
 return OMX_ErrorUnsupportedSetting;
 }
 break;
 }
 case OMX_QcomIndexParamPeakBitrate:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_VIDEO_PARAM_PEAK_BITRATE);
 if (!handle->venc_set_param(paramData,
 (OMX_INDEXTYPE) OMX_QcomIndexParamPeakBitrate)) {
                    DEBUG_PRINT_ERROR("ERROR: Setting peak bitrate");
 return OMX_ErrorUnsupportedSetting;
 }
 break;
 }
 case QOMX_IndexParamVideoInitialQp:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, QOMX_EXTNINDEX_VIDEO_INITIALQP);
 if(!handle->venc_set_param(paramData,
 (OMX_INDEXTYPE)QOMX_IndexParamVideoInitialQp)) {
                    DEBUG_PRINT_ERROR("Request to Enable initial QP failed");
 return OMX_ErrorUnsupportedSetting;
 }
                memcpy(&m_sParamInitqp, paramData, sizeof(m_sParamInitqp));
 break;
 }
 case OMX_QcomIndexParamSetMVSearchrange:
 {
 if (!handle->venc_set_param(paramData,
 (OMX_INDEXTYPE) OMX_QcomIndexParamSetMVSearchrange)) {
                    DEBUG_PRINT_ERROR("ERROR: Setting Searchrange");
 return OMX_ErrorUnsupportedSetting;
 }
 break;
 }
 case OMX_QcomIndexParamVideoHybridHierpMode:
 {
                VALIDATE_OMX_PARAM_DATA(paramData, QOMX_EXTNINDEX_VIDEO_HYBRID_HP_MODE);
 if(!handle->venc_set_param(paramData,
 (OMX_INDEXTYPE)OMX_QcomIndexParamVideoHybridHierpMode)) {
                   DEBUG_PRINT_ERROR("Request to Enable Hybrid Hier-P failed");
 return OMX_ErrorUnsupportedSetting;
 }
 break;
 }
 case OMX_IndexParamVideoSliceFMO:
 default:
 {
                DEBUG_PRINT_ERROR("ERROR: Setparameter: unknown param %d", paramIndex);
                eRet = OMX_ErrorUnsupportedIndex;
 break;
 }
 }
 return eRet;
}


uint64_t ldq_phys(target_phys_addr_t addr)

{

    return ldq_phys_internal(addr, DEVICE_NATIVE_ENDIAN);

}


static int get_rdrand_seed()
{
    DEBUG_SEED("get_rdrand_seed");
    int _eax;
    // rdrand eax
    __asm__ __volatile__("1: .byte 0x0F\n"
                         "   .byte 0xC7\n"
                         "   .byte 0xF0\n"
                         "   jnc 1b;\n"
                         : "=a" (_eax));
    return _eax;
}


void Gfx::opEndPath(Object args[], int numArgs) {
  doEndPath();
}


int ping_common_sendmsg(int family, struct msghdr *msg, size_t len,
			void *user_icmph, size_t icmph_len) {
	u8 type, code;

	if (len > 0xFFFF)
		return -EMSGSIZE;

	/*
	 *	Check the flags.
	 */

	/* Mirror BSD error message compatibility */
	if (msg->msg_flags & MSG_OOB)
		return -EOPNOTSUPP;

	/*
	 *	Fetch the ICMP header provided by the userland.
	 *	iovec is modified! The ICMP header is consumed.
	 */
	if (memcpy_from_msg(user_icmph, msg, icmph_len))
		return -EFAULT;

	if (family == AF_INET) {
		type = ((struct icmphdr *) user_icmph)->type;
		code = ((struct icmphdr *) user_icmph)->code;
#if IS_ENABLED(CONFIG_IPV6)
	} else if (family == AF_INET6) {
		type = ((struct icmp6hdr *) user_icmph)->icmp6_type;
		code = ((struct icmp6hdr *) user_icmph)->icmp6_code;
#endif
	} else {
		BUG();
	}

	if (!ping_supported(family, type, code))
		return -EINVAL;

	return 0;
}


ScriptPromise HTMLMediaElement::playForBindings(ScriptState* scriptState) {
  ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
  ScriptPromise promise = resolver->promise();
  m_playPromiseResolvers.push_back(resolver);

  Nullable<ExceptionCode> code = play();
  if (!code.isNull()) {
    DCHECK(!m_playPromiseResolvers.isEmpty());
    m_playPromiseResolvers.pop_back();

    String message;
    switch (code.get()) {
      case NotAllowedError:
        message = "play() can only be initiated by a user gesture.";
        break;
      case NotSupportedError:
        message = "The element has no supported sources.";
        break;
      default:
        NOTREACHED();
    }
    resolver->reject(DOMException::create(code.get(), message));
    return promise;
  }

  return promise;
}


compressVerify (const unsigned short raw[],
                int n,
                const unsigned int dekHash)
{
    Array <char> compressed (3 * n + 4 * 65536);

    int nCompressed = hufCompress (raw, n, compressed);

    //
    // This hash algorithm proposed by Donald E. Knuth in
    // The Art Of Computer Programming Volume 3,
    // under the topic of sorting and search chapter 6.4.
    //
    unsigned int compressedHash = nCompressed;
    const unsigned char* cptr = reinterpret_cast<const unsigned char*>( (const char*) compressed);
    for (int i = 0; i < nCompressed; ++i)
    {
        compressedHash =
            ((compressedHash << 5) ^ (compressedHash >> 27)) ^ (*cptr++);
    }

    cout << "verifying compressed checksum hash = "
        << compressedHash << std::endl;

    if (compressedHash != dekHash)
    {
       cout << "hash verification failed. Got " << compressedHash << " expected " << dekHash << std::endl;
       const unsigned char* cptr = reinterpret_cast<const unsigned char*>( (const char*) compressed);
       for(int i = 0 ; i < nCompressed ; ++i )
       {
           cout << std::hex << (0xFF & (int) (*cptr++));
           if ( (i & 0xF) ==0 )
           {
              cout << '\n';
           }
           else
           {
              cout << ' ';
           }
       }
       cout << "\n";
    }

    assert (compressedHash == dekHash);
}


TEST_P(Http2IntegrationTest, Retry) { testRetry(); }


int kvmppc_remove_spapr_tce(void *table, int fd, uint32_t window_size)

{

    long len;

    if (fd < 0) {

        return -1;

    }

    len = (window_size / SPAPR_VIO_TCE_PAGE_SIZE)*sizeof(VIOsPAPR_RTCE);

    if ((munmap(table, len) < 0) ||

        (close(fd) < 0)) {

        fprintf(stderr, "KVM: Unexpected error removing KVM SPAPR TCE "

                "table: %s", strerror(errno));

        /* Leak the table */

    }

    return 0;

}


BOOL license_read_license_request_packet(rdpLicense* license, wStream* s)
{
	/* ServerRandom (32 bytes) */
	if (Stream_GetRemainingLength(s) < 32)
		return FALSE;

	Stream_Read(s, license->ServerRandom, 32);

	/* ProductInfo */
	if (!license_read_product_info(s, license->ProductInfo))
		return FALSE;

	/* KeyExchangeList */
	if (!license_read_binary_blob(s, license->KeyExchangeList))
		return FALSE;

	/* ServerCertificate */
	if (!license_read_binary_blob(s, license->ServerCertificate))
		return FALSE;

	/* ScopeList */
	if (!license_read_scope_list(s, license->ScopeList))
		return FALSE;

	/* Parse Server Certificate */
	if (!certificate_read_server_certificate(license->certificate,
			license->ServerCertificate->data, license->ServerCertificate->length) < 0)
		return FALSE;

	license_generate_keys(license);
	license_generate_hwid(license);
	license_encrypt_premaster_secret(license);

#ifdef WITH_DEBUG_LICENSE
	fprintf(stderr, "ServerRandom:\n");
	winpr_HexDump(license->ServerRandom, 32);
	fprintf(stderr, "\n");

	license_print_product_info(license->ProductInfo);
	fprintf(stderr, "\n");

	license_print_scope_list(license->ScopeList);
	fprintf(stderr, "\n");
#endif

	return TRUE;
}


static void ohci_hard_reset(OHCIState *ohci)
{
    ohci_soft_reset(ohci);
    ohci->ctl = 0;
    ohci_roothub_reset(ohci);
}


WebRunnerBrowserContext::GetSSLHostStateDelegate() {
  return nullptr;
}


std::shared_ptr<rss_feed> controller::get_feed(unsigned int pos) {
	std::lock_guard<std::mutex> feedslock(feeds_mutex);
	if (pos >= feeds.size()) {
		throw std::out_of_range(_("invalid feed index (bug)"));
	}
	std::shared_ptr<rss_feed> feed = feeds[pos];
	return feed;
}


acpi_status __init acpi_os_initialize(void)
{
	acpi_os_map_generic_address(&acpi_gbl_FADT.xpm1a_event_block);
	acpi_os_map_generic_address(&acpi_gbl_FADT.xpm1b_event_block);
	acpi_os_map_generic_address(&acpi_gbl_FADT.xgpe0_block);
	acpi_os_map_generic_address(&acpi_gbl_FADT.xgpe1_block);
	if (acpi_gbl_FADT.flags & ACPI_FADT_RESET_REGISTER) {
		/*
		 * Use acpi_os_map_generic_address to pre-map the reset
		 * register if it's in system memory.
		 */
		int rv;

		rv = acpi_os_map_generic_address(&acpi_gbl_FADT.reset_register);
		pr_debug(PREFIX "%s: map reset_reg status %d\n", __func__, rv);
	}
	acpi_os_initialized = true;

	return AE_OK;
}


static void pdf_run_sc_shade ( fz_context * ctx , pdf_processor * proc , const char * name , fz_shade * shade ) {
 pdf_run_processor * pr = ( pdf_run_processor * ) proc ;
 pr -> dev -> flags &= ~ FZ_DEVFLAG_FILLCOLOR_UNDEFINED ;
 pdf_set_shade ( ctx , pr , PDF_FILL , shade ) ;
 }


AioContext *aio_context_new(void)

{

    return (AioContext *) g_source_new(&aio_source_funcs, sizeof(AioContext));

}


int hns_ppe_get_sset_count(int stringset)
{
	if (stringset == ETH_SS_STATS || stringset == ETH_SS_PRIV_FLAGS)
		return ETH_PPE_STATIC_NUM;
	return 0;
}


static int vp9_raw_reorder_make_output(AVBSFContext *bsf,

                                   AVPacket *out,

                                   VP9RawReorderFrame *last_frame)

{

    VP9RawReorderContext *ctx = bsf->priv_data;

    VP9RawReorderFrame *next_output = last_frame,

                      *next_display = last_frame, *frame;

    int s, err;

    for (s = 0; s < FRAME_SLOTS; s++) {

        frame = ctx->slot[s];

        if (!frame)

            continue;

        if (frame->needs_output && (!next_output ||

            frame->sequence < next_output->sequence))

            next_output = frame;

        if (frame->needs_display && (!next_display ||

            frame->pts < next_display->pts))

            next_display = frame;

    }

    if (!next_output && !next_display)

        return AVERROR_EOF;

    if (!next_display || (next_output &&

        next_output->sequence < next_display->sequence))

        frame = next_output;

    else

        frame = next_display;

    if (frame->needs_output && frame->needs_display &&

        next_output == next_display) {

        av_log(bsf, AV_LOG_DEBUG, "Output and display frame "

               "%"PRId64" (%"PRId64") in order.\n",

               frame->sequence, frame->pts);

        av_packet_move_ref(out, frame->packet);

        frame->needs_output = frame->needs_display = 0;

    } else if (frame->needs_output) {

        if (frame->needs_display) {

            av_log(bsf, AV_LOG_DEBUG, "Output frame %"PRId64" "

                   "(%"PRId64") for later display.\n",

                   frame->sequence, frame->pts);

        } else {

            av_log(bsf, AV_LOG_DEBUG, "Output unshown frame "

                   "%"PRId64" (%"PRId64") to keep order.\n",

                   frame->sequence, frame->pts);

        }

        av_packet_move_ref(out, frame->packet);

        out->pts = out->dts;

        frame->needs_output = 0;

    } else {

        PutBitContext pb;

        av_assert0(!frame->needs_output && frame->needs_display);

        if (frame->slots == 0) {

            av_log(bsf, AV_LOG_ERROR, "Attempting to display frame "

                   "which is no longer available?\n");

            frame->needs_display = 0;

            return AVERROR_INVALIDDATA;

        }

        s = ff_ctz(frame->slots);

        av_assert0(s < FRAME_SLOTS);

        av_log(bsf, AV_LOG_DEBUG, "Display frame %"PRId64" "

               "(%"PRId64") from slot %d.\n",

               frame->sequence, frame->pts, s);

        frame->packet = av_packet_alloc();

        if (!frame->packet)

            return AVERROR(ENOMEM);

        err = av_new_packet(out, 2);

        if (err < 0)

            return err;

        init_put_bits(&pb, out->data, 2);

        // frame_marker

        put_bits(&pb, 2, 2);

        // profile_low_bit

        put_bits(&pb, 1, frame->profile & 1);

        // profile_high_bit

        put_bits(&pb, 1, (frame->profile >> 1) & 1);

        if (frame->profile == 3) {

            // reserved_zero

            put_bits(&pb, 1, 0);

        }

        // show_existing_frame

        put_bits(&pb, 1, 1);

        // frame_to_show_map_idx

        put_bits(&pb, 3, s);

        while (put_bits_count(&pb) < 16)

            put_bits(&pb, 1, 0);

        flush_put_bits(&pb);

        out->pts = out->dts = frame->pts;

        frame->needs_display = 0;

    }

    return 0;

}


int el_draft_message(LOGBOOK *lbs, int message_id, char *user, BOOL bdraft)
/* lock message for editing */
{
   int size;
   char date[80], attrib[MAX_N_ATTR][NAME_LENGTH], text[TEXT_SIZE], in_reply_to[80],
           reply_to[MAX_REPLY_TO * 10], encoding[80], locked_by[256], draft[256];
   char att_file[MAX_ATTACHMENTS][256];

   /* retrieve message */
   size = sizeof(text);
   el_retrieve(lbs, message_id, date, attr_list, attrib, lbs->n_attr, text, &size, in_reply_to, reply_to,
               att_file, encoding, locked_by, draft);

   /* submit message, undraft if bdraft == FALSE */
   el_submit(lbs, message_id, TRUE, date, attr_list, attrib, lbs->n_attr, text, in_reply_to, reply_to,
             encoding, att_file, FALSE, locked_by, bdraft ? user : NULL);

   return EL_SUCCESS;
}


static bool r_bin_mdmp_patch_pe_headers(RBuffer *pe_buf) {
	int i;
	Pe64_image_dos_header dos_hdr;
	Pe64_image_nt_headers nt_hdr;
	Pe64_image_section_header *section_hdrs;

	r_buf_read_at (pe_buf, 0, (ut8 *)&dos_hdr, sizeof (Pe64_image_dos_header));
	r_buf_read_at (pe_buf, dos_hdr.e_lfanew, (ut8 *)&nt_hdr, sizeof (Pe64_image_nt_headers));

	/* Patch RawData in headers */
	section_hdrs = (Pe64_image_section_header *)(pe_buf->buf + dos_hdr.e_lfanew + 4 + sizeof (Pe64_image_file_header) + nt_hdr.file_header.SizeOfOptionalHeader);
	for (i = 0; i < nt_hdr.file_header.NumberOfSections; i++) {
		section_hdrs[i].PointerToRawData = section_hdrs[i].VirtualAddress;
	}

	return true;
}


void qmp_migrate_set_downtime(double value, Error **errp)

{

    value *= 1e9;

    value = MAX(0, MIN(UINT64_MAX, value));

    max_downtime = (uint64_t)value;

}


static int parse_CCoercionRestriction ( tvbuff_t * tvb , int offset , proto_tree * parent_tree , proto_tree * pad_tree , struct CCoercionRestriction * v , const char * fmt , ... ) {
 proto_tree * tree ;
 proto_item * item ;
 const char * txt ;
 va_list ap ;
 va_start ( ap , fmt ) ;
 txt = wmem_strdup_vprintf ( wmem_packet_scope ( ) , fmt , ap ) ;
 va_end ( ap ) ;
 tree = proto_tree_add_subtree ( parent_tree , tvb , offset , 0 , ett_CCoercionRestriction , & item , txt ) ;
 v -> value = tvb_get_letohieee_float ( tvb , offset ) ;
 proto_tree_add_float ( tree , hf_mswsp_ccoercerestrict_value , tvb , offset , 4 , v -> value ) ;
 offset += 4 ;
 offset = parse_CRestriction ( tvb , offset , tree , pad_tree , & v -> child , "child" ) ;
 proto_item_set_end ( item , tvb , offset ) ;
 return offset ;
 }


TEST_F(RouterTest, TimeoutBudgetHistogramStat) {
  NiceMock<Http::MockRequestEncoder> encoder;
  Http::ResponseDecoder* response_decoder = nullptr;
  expectNewStreamWithImmediateEncoder(encoder, &response_decoder, Http::Protocol::Http10);

  expectPerTryTimerCreate();
  expectResponseTimerCreate();

  Http::TestRequestHeaderMapImpl headers{{"x-envoy-upstream-rq-timeout-ms", "400"},
                                         {"x-envoy-upstream-rq-per-try-timeout-ms", "200"}};
  HttpTestUtility::addDefaultHeaders(headers);
  router_.decodeHeaders(headers, false);
  Buffer::OwnedImpl data;
  router_.decodeData(data, true);
  EXPECT_EQ(1U,
            callbacks_.route_->route_entry_.virtual_cluster_.stats().upstream_rq_total_.value());

  // Global timeout budget used.
  EXPECT_CALL(
      cm_.thread_local_cluster_.cluster_.info_->timeout_budget_stats_store_,
      deliverHistogramToSinks(
          Property(&Stats::Metric::name, "upstream_rq_timeout_budget_percent_used"), 20ull));
  // Per-try budget used.
  EXPECT_CALL(cm_.thread_local_cluster_.cluster_.info_->timeout_budget_stats_store_,
              deliverHistogramToSinks(
                  Property(&Stats::Metric::name, "upstream_rq_timeout_budget_per_try_percent_used"),
                  40ull));

  Http::ResponseHeaderMapPtr response_headers(
      new Http::TestResponseHeaderMapImpl{{":status", "200"}});
  response_decoder->decodeHeaders(std::move(response_headers), false);
  test_time_.advanceTimeWait(std::chrono::milliseconds(80));
  response_decoder->decodeData(data, true);
}


_flatpak_dir_get_remote_state (FlatpakDir   *self,
                               const char   *remote_or_uri,
                               gboolean      optional,
                               gboolean      local_only,
                               gboolean      only_cached,
                               gboolean      opt_summary_is_index,
                               GBytes       *opt_summary,
                               GBytes       *opt_summary_sig,
                               GCancellable *cancellable,
                               GError      **error)
{
  g_autoptr(FlatpakRemoteState) state = flatpak_remote_state_new ();
  g_autoptr(GPtrArray) sideload_paths = NULL;
  g_autofree char *url = NULL;
  g_autoptr(GError) my_error = NULL;
  gboolean is_local;
  gboolean got_summary = FALSE;
  const char *arch = flatpak_get_default_arch ();
  g_autoptr(GBytes) index_bytes = NULL;
  g_autoptr(GBytes) index_sig_bytes = NULL;
  g_autoptr(GBytes) summary_bytes = NULL;
  g_autoptr(GBytes) summary_sig_bytes = NULL;

  if (error == NULL)
    error = &my_error;

  if (!flatpak_dir_ensure_repo (self, cancellable, error))
    return NULL;

  state->remote_name = g_strdup (remote_or_uri);
  state->is_file_uri = is_local = g_str_has_prefix (remote_or_uri, "file:");
  if (!is_local)
    {
      if (!flatpak_dir_has_remote (self, remote_or_uri, error))
        return NULL;
      if (!repo_get_remote_collection_id (self->repo, remote_or_uri, &state->collection_id, error))
        return NULL;
      if (!flatpak_dir_lookup_remote_filter (self, remote_or_uri, FALSE, NULL, &state->allow_refs, &state->deny_refs, error))
        return NULL;
      if (!ostree_repo_remote_get_url (self->repo, remote_or_uri, &url, error))
        return NULL;

      state->default_token_type = flatpak_dir_get_remote_default_token_type (self, remote_or_uri);
    }

  sideload_paths = flatpak_dir_get_sideload_repo_paths (self);
  for (int i = 0; i < sideload_paths->len; i++)
    flatpak_remote_state_add_sideload_repo (state, g_ptr_array_index (sideload_paths, i));

  if (local_only)
    {
      flatpak_fail (&state->summary_fetch_error, "Internal error, local_only state");
      return g_steal_pointer (&state);
    }

  if (opt_summary)
    {
      if (opt_summary_sig)
        {
          /* If specified, must be valid signature */
          g_autoptr(OstreeGpgVerifyResult) gpg_result =
            ostree_repo_verify_summary (self->repo,
                                        state->remote_name,
                                        opt_summary,
                                        opt_summary_sig,
                                        NULL, error);
          if (gpg_result == NULL ||
              !ostree_gpg_verify_result_require_valid_signature (gpg_result, error))
            return NULL;
        }

      if (opt_summary_is_index)
        {
          if (opt_summary_sig)
            index_sig_bytes = g_bytes_ref (opt_summary_sig);
          index_bytes = g_bytes_ref (opt_summary);
        }
      else
        {
          if (opt_summary_sig)
            summary_sig_bytes = g_bytes_ref (opt_summary_sig);
          summary_bytes = g_bytes_ref (opt_summary);
        }

      got_summary = TRUE;
    }

  /* First try the memory cache. Note: No in-memory caching for local files. */
  if (!is_local)
    {
      if (!got_summary)
        {
          g_autofree char *index_cache_key = g_strconcat ("index-", remote_or_uri, NULL);
          if (flatpak_dir_lookup_cached_summary (self, &index_bytes, &index_sig_bytes, index_cache_key, url))
            got_summary = TRUE;
        }

      if (!got_summary)
        {
          g_autofree char *summary_cache_key = g_strconcat ("summary-", remote_or_uri, NULL);
          if (flatpak_dir_lookup_cached_summary (self, &summary_bytes, &summary_sig_bytes, summary_cache_key, url))
            got_summary = TRUE;
        }
    }

  /* Then look for an indexed summary on disk/network */
  if (!got_summary)
    {
      g_autoptr(GError) local_error = NULL;

      if (flatpak_dir_remote_fetch_summary_index (self, remote_or_uri, only_cached, &index_bytes, &index_sig_bytes,
                                                  cancellable, &local_error))
        {
          got_summary = TRUE;
        }
      else
        {
          if (!g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND) &&
              !g_error_matches (local_error, FLATPAK_ERROR, FLATPAK_ERROR_NOT_CACHED))
            {
              /* We got an error other than not-found, assume we're indexed but there is some network error */
              got_summary = TRUE;
              if (optional && !g_cancellable_is_cancelled (cancellable))
                {
                  g_debug ("Failed to download optional summary index: %s", local_error->message);
                  state->summary_fetch_error = g_steal_pointer (&local_error);
                }
              else
                {
                  g_propagate_error (error, g_steal_pointer (&local_error));
                  return NULL;
                }
            }
        }
    }

  if (!got_summary)
    {
      /* No index, fall back to full summary */
      g_autoptr(GError) local_error = NULL;

      if (flatpak_dir_remote_fetch_summary (self, remote_or_uri, only_cached, &summary_bytes, &summary_sig_bytes,
                                            cancellable, &local_error))
        {
          got_summary = TRUE;
        }
      else
        {
          if (optional && !g_cancellable_is_cancelled (cancellable))
            {
              g_debug ("Failed to download optional summary: %s", local_error->message);
              state->summary_fetch_error = g_steal_pointer (&local_error);
            }
          else
            {
              g_propagate_error (error, g_steal_pointer (&local_error));
              return NULL;
            }
        }
    }

  if (index_bytes)
    {
      state->index = g_variant_ref_sink (g_variant_new_from_bytes (FLATPAK_SUMMARY_INDEX_GVARIANT_FORMAT,
                                                                   index_bytes, FALSE));
      state->index_sig_bytes = g_steal_pointer (&index_sig_bytes);
    }
  else if (summary_bytes)
    {
      state->summary = g_variant_ref_sink (g_variant_new_from_bytes (OSTREE_SUMMARY_GVARIANT_FORMAT,
                                                                     summary_bytes, FALSE));
      state->summary_bytes = g_steal_pointer (&summary_bytes);
      state->summary_sig_bytes = g_steal_pointer (&summary_sig_bytes);
    }

  if (state->index)
    {
      g_autofree char *require_subset = flatpak_dir_get_remote_subset (self, state->remote_name);
      VarSummaryIndexRef index = var_summary_index_from_gvariant (state->index);
      VarSummaryIndexSubsummariesRef subsummaries = var_summary_index_get_subsummaries (index);
      gsize n_subsummaries = var_summary_index_subsummaries_get_length (subsummaries);

      state->index_ht = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)g_variant_unref);

      for (gsize i = 0; i < n_subsummaries; i++)
        {
          VarSummaryIndexSubsummariesEntryRef entry = var_summary_index_subsummaries_get_at (subsummaries, i);
          const char *name = var_summary_index_subsummaries_entry_get_key (entry);
          VarSubsummaryRef subsummary = var_summary_index_subsummaries_entry_get_value (entry);
          gsize checksum_bytes_len;
          const char *dash, *subsummary_arch;

          dash = strchr (name, '-');
          subsummary_arch = dash == NULL ? name : dash + 1;

          if (dash == NULL) /* No subset */
            {
              if (require_subset != NULL)
                continue;
            }
          else /* Subset */
            {
              if (require_subset == NULL)
                continue;
              else
                {
                  g_autofree char *subset = g_strndup (name, dash - name);
                  if (strcmp (require_subset, subset) != 0)
                    continue;
                }
            }

          var_subsummary_peek_checksum (subsummary, &checksum_bytes_len);
          if (G_UNLIKELY (checksum_bytes_len != OSTREE_SHA256_DIGEST_LEN))
            {
              g_debug ("Invalid checksum for digested summary, not using cache");
              continue;
            }

          g_hash_table_insert (state->index_ht, g_strdup (subsummary_arch), var_subsummary_to_owned_gvariant (subsummary, state->index));
        }

      /* Always load default (or specified) arch subsummary. Further arches can be manually loaded with flatpak_remote_state_ensure_subsummary. */
      if (opt_summary == NULL &&
          !flatpak_remote_state_ensure_subsummary (state, self, arch, only_cached, cancellable, error))
        return NULL;
    }

  if (state->collection_id != NULL &&
      state->summary != NULL &&
      !_validate_summary_for_collection_id (state->summary, state->collection_id, error))
    return NULL;

  if (flatpak_dir_get_remote_oci (self, remote_or_uri))
    {
      state->default_token_type = 1;
    }

  if (state->summary != NULL || state->index != NULL) /* In the optional case we might not have a summary */
    {
      VarMetadataRef meta = flatpak_remote_state_get_main_metadata (state);
      VarVariantRef res;

      if (var_metadata_lookup (meta, "xa.default-token-type", NULL, &res) &&
          var_variant_is_type (res, G_VARIANT_TYPE_INT32))
        state->default_token_type = GINT32_FROM_LE (var_variant_get_int32 (res));
    }

  return g_steal_pointer (&state);
}


static int dissect_pvfs_ds_keyval ( tvbuff_t * tvb , proto_tree * tree , int offset ) {
 offset = dissect_pvfs_string ( tvb , tree , hf_pvfs_attribute_key , offset , NULL ) ;
 offset = dissect_pvfs_string ( tvb , tree , hf_pvfs_attribute_value , offset , NULL ) ;
 return offset ;
 }


void CLASS parse_minolta (int base)
{
  int save, tag, len, offset, high=0, wide=0, i, c;
  short sorder=order;

  fseek (ifp, base, SEEK_SET);
  if (fgetc(ifp) || fgetc(ifp)-'M' || fgetc(ifp)-'R') return;
  order = fgetc(ifp) * 0x101;
  offset = base + get4() + 8;
#ifdef LIBRAW_LIBRARY_BUILD
  if(offset>ifp->size()-8) // At least 8 bytes for tag/len
    offset = ifp->size()-8;
#endif
  while ((save=ftell(ifp)) < offset) {
    for (tag=i=0; i < 4; i++)
      tag = tag << 8 | fgetc(ifp);
    len = get4();
    if(len < 0)
      return; // just ignore wrong len?? or raise bad file exception?
    switch (tag) {
      case 0x505244:				/* PRD */
	fseek (ifp, 8, SEEK_CUR);
	high = get2();
	wide = get2();
	break;
#ifdef LIBRAW_LIBRARY_BUILD
      case 0x524946:				/* RIF */
    if (!strncasecmp(model,"DSLR-A100", 9))
    {
      fseek(ifp, 8, SEEK_CUR);
      imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2();
      get4();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2();
      imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] =
        imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] =
        imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] =
        imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] =
        imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] =
        imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] =
        imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] =
        imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] =
        imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100;
    }
	break;
#endif
      case 0x574247:				/* WBG */
	get4();
	i = strcmp(model,"DiMAGE A200") ? 0:3;
	FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2();
	break;
      case 0x545457:				/* TTW */
	parse_tiff (ftell(ifp));
	data_offset = offset;
    }
    fseek (ifp, save+len+8, SEEK_SET);
  }
  raw_height = high;
  raw_width  = wide;
  order = sorder;
}


inline void AndPredicate::accept(Visitor &v) { v.visit(*this); }


bool JSTestInterfaceConstructor::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
    return getStaticPropertySlot<JSTestInterfaceConstructor, JSDOMWrapper>(exec, &JSTestInterfaceConstructorTable, jsCast<JSTestInterfaceConstructor*>(cell), propertyName, slot);
}


static int write_note_info(struct elf_note_info *info,
			   struct coredump_params *cprm)
{
	int i;
	struct list_head *t;

	for (i = 0; i < info->numnote; i++)
		if (!writenote(info->notes + i, cprm))
			return 0;

	/* write out the thread status notes section */
	list_for_each(t, &info->thread_list) {
		struct elf_thread_status *tmp =
				list_entry(t, struct elf_thread_status, list);

		for (i = 0; i < tmp->num_notes; i++)
			if (!writenote(&tmp->notes[i], cprm))
				return 0;
	}

	return 1;
}


void Document::setStateForNewFormElements(const Vector<String>& stateVector)
{
    if (!stateVector.size() && !m_formController)
        return;
    formController().setStateForNewFormElements(stateVector);
}


  void initializeFilter(bool add_cluster) {
    config_helper_.prependFilter(getFilterConfig(false));

    if (add_cluster) {
      config_helper_.addConfigModifier([](envoy::config::bootstrap::v3::Bootstrap& bootstrap) {
        auto* jwks_cluster = bootstrap.mutable_static_resources()->add_clusters();
        jwks_cluster->MergeFrom(bootstrap.static_resources().clusters()[0]);
        jwks_cluster->set_name("pubkey_cluster");
      });
    } else {
      config_helper_.skipPortUsageValidation();
    }

    initialize();
  }


static struct bfq_queue *
bfq_rq_pos_tree_lookup(struct bfq_data *bfqd, struct rb_root *root,
		     sector_t sector, struct rb_node **ret_parent,
		     struct rb_node ***rb_link)
{
	struct rb_node **p, *parent;
	struct bfq_queue *bfqq = NULL;

	parent = NULL;
	p = &root->rb_node;
	while (*p) {
		struct rb_node **n;

		parent = *p;
		bfqq = rb_entry(parent, struct bfq_queue, pos_node);

		/*
		 * Sort strictly based on sector. Smallest to the left,
		 * largest to the right.
		 */
		if (sector > blk_rq_pos(bfqq->next_rq))
			n = &(*p)->rb_right;
		else if (sector < blk_rq_pos(bfqq->next_rq))
			n = &(*p)->rb_left;
		else
			break;
		p = n;
		bfqq = NULL;
	}

	*ret_parent = parent;
	if (rb_link)
		*rb_link = p;

	bfq_log(bfqd, "rq_pos_tree_lookup %llu: returning %d",
		(unsigned long long)sector,
		bfqq ? bfqq->pid : 0);

	return bfqq;


static gboolean webkit_web_view_drag_motion(GtkWidget* widget, GdkDragContext* context, gint x, gint y, guint time)
{
    WebKitWebView* webView = WEBKIT_WEB_VIEW(widget);
    WebKitWebViewPrivate* priv = webView->priv;

    DroppingContext* droppingContext = 0;
    IntPoint position = IntPoint(x, y);
    if (!priv->droppingContexts.contains(context)) {
        droppingContext = new DroppingContext;
        droppingContext->webView = webView;
        droppingContext->gdkContext = context;
        droppingContext->dataObject = WebCore::DataObjectGtk::create();
        droppingContext->dropHappened = false;
        droppingContext->lastMotionPosition = position;
        priv->droppingContexts.set(context, droppingContext);

        Vector<GdkAtom> acceptableTargets(pasteboardHelperInstance()->dropAtomsForContext(widget, context));
        droppingContext->pendingDataRequests = acceptableTargets.size();
        for (size_t i = 0; i < acceptableTargets.size(); i++)
            gtk_drag_get_data(widget, context, acceptableTargets.at(i), time);
    } else {
        droppingContext = priv->droppingContexts.get(context);
        droppingContext->lastMotionPosition = position;
    }

    ASSERT(droppingContext);
    if (droppingContext->pendingDataRequests > 0)
        return TRUE;

    DragData dragData(droppingContext->dataObject.get(), position, globalPointForClientPoint(gtk_widget_get_window(widget), position), gdkDragActionToDragOperation(gdk_drag_context_get_actions(context)));
    DragOperation operation = core(webView)->dragController()->dragUpdated(&dragData);
    gdk_drag_status(context, dragOperationToSingleGdkDragAction(operation), time);

    return TRUE;
}


static void ihevcd_fill_outargs(codec_t *ps_codec,
 ivd_video_decode_ip_t *ps_dec_ip,
 ivd_video_decode_op_t *ps_dec_op)
{

    ps_dec_op->u4_error_code = ihevcd_map_error((IHEVCD_ERROR_T)ps_codec->i4_error_code);
    ps_dec_op->u4_num_bytes_consumed = ps_dec_ip->u4_num_Bytes
 - ps_codec->i4_bytes_remaining;
 if(ps_codec->i4_sps_done)
 {
        ps_dec_op->u4_pic_wd = ps_codec->i4_disp_wd;
        ps_dec_op->u4_pic_ht = ps_codec->i4_disp_ht;
 }
 else
 {
        ps_dec_op->u4_pic_wd = 0;
        ps_dec_op->u4_pic_ht = 0;
 }

    ps_dec_op->e_pic_type = ps_codec->e_dec_pic_type;
    ps_dec_op->u4_frame_decoded_flag = ps_codec->i4_pic_present;
    ps_dec_op->u4_new_seq = 0;

    ps_dec_op->u4_output_present = 0;
    ps_dec_op->u4_progressive_frame_flag = 1;
    ps_dec_op->u4_is_ref_flag = 1;
    ps_dec_op->e_output_format = ps_codec->e_chroma_fmt;
    ps_dec_op->u4_is_ref_flag = 1;

    ps_dec_op->e4_fld_type = IV_FLD_TYPE_DEFAULT;

    ps_dec_op->u4_ts = (UWORD32)(-1);
    ps_dec_op->u4_disp_buf_id = ps_codec->i4_disp_buf_id;
 if(ps_codec->i4_flush_mode)
 {
        ps_dec_op->u4_num_bytes_consumed = 0;
 /*In the case of flush ,since no frame is decoded set pic type as invalid*/
        ps_dec_op->u4_is_ref_flag = 0;
        ps_dec_op->e_pic_type = IV_NA_FRAME;
        ps_dec_op->u4_frame_decoded_flag = 0;

 }
 /* If there is a display buffer */
 if(ps_codec->ps_disp_buf)
 {
 pic_buf_t *ps_disp_buf = ps_codec->ps_disp_buf;

        ps_dec_op->u4_output_present = 1;
        ps_dec_op->u4_ts = ps_disp_buf->u4_ts;
 if((ps_codec->i4_flush_mode == 0) && (ps_codec->s_parse.i4_end_of_frame == 0))
            ps_dec_op->u4_output_present = 0;
        ps_dec_op->s_disp_frm_buf.u4_y_wd = ps_codec->i4_disp_wd;
        ps_dec_op->s_disp_frm_buf.u4_y_ht = ps_codec->i4_disp_ht;

 if(ps_codec->i4_share_disp_buf)
 {
            ps_dec_op->s_disp_frm_buf.pv_y_buf = ps_disp_buf->pu1_luma;
 if(ps_codec->e_chroma_fmt != IV_YUV_420P)
 {
                ps_dec_op->s_disp_frm_buf.pv_u_buf = ps_disp_buf->pu1_chroma;
                ps_dec_op->s_disp_frm_buf.pv_v_buf = NULL;
 }
 else
 {
                WORD32 i;
                UWORD8 *pu1_u_dst = NULL, *pu1_v_dst = NULL;
 for(i = 0; i < ps_codec->i4_share_disp_buf_cnt; i++)
 {
                    WORD32 diff = ps_disp_buf->pu1_luma - ps_codec->s_disp_buffer[i].pu1_bufs[0];
 if(diff == (ps_codec->i4_strd * PAD_TOP + PAD_LEFT))
 {
                        pu1_u_dst = ps_codec->s_disp_buffer[i].pu1_bufs[1];
                        pu1_u_dst += (ps_codec->i4_strd * PAD_TOP) / 4 + (PAD_LEFT / 2);

                        pu1_v_dst = ps_codec->s_disp_buffer[i].pu1_bufs[2];
                        pu1_v_dst += (ps_codec->i4_strd * PAD_TOP) / 4 + (PAD_LEFT / 2);
 break;
 }
 }
                ps_dec_op->s_disp_frm_buf.pv_u_buf = pu1_u_dst;
                ps_dec_op->s_disp_frm_buf.pv_v_buf = pu1_v_dst;
 }
            ps_dec_op->s_disp_frm_buf.u4_y_strd = ps_codec->i4_strd;
 }
 else
 {
            ps_dec_op->s_disp_frm_buf.pv_y_buf =
                            ps_dec_ip->s_out_buffer.pu1_bufs[0];
            ps_dec_op->s_disp_frm_buf.pv_u_buf =
                            ps_dec_ip->s_out_buffer.pu1_bufs[1];
            ps_dec_op->s_disp_frm_buf.pv_v_buf =
                            ps_dec_ip->s_out_buffer.pu1_bufs[2];
            ps_dec_op->s_disp_frm_buf.u4_y_strd = ps_codec->i4_disp_strd;
 }

 if((IV_YUV_420SP_VU == ps_codec->e_chroma_fmt)
 || (IV_YUV_420SP_UV == ps_codec->e_chroma_fmt))
 {
            ps_dec_op->s_disp_frm_buf.u4_u_strd =
                            ps_dec_op->s_disp_frm_buf.u4_y_strd;
            ps_dec_op->s_disp_frm_buf.u4_v_strd = 0;
            ps_dec_op->s_disp_frm_buf.u4_u_wd =
                            ps_dec_op->s_disp_frm_buf.u4_y_wd;
            ps_dec_op->s_disp_frm_buf.u4_v_wd = 0;
            ps_dec_op->s_disp_frm_buf.u4_u_ht =
                            ps_dec_op->s_disp_frm_buf.u4_y_ht / 2;
            ps_dec_op->s_disp_frm_buf.u4_v_ht = 0;
 }
 else if(IV_YUV_420P == ps_codec->e_chroma_fmt)
 {
            ps_dec_op->s_disp_frm_buf.u4_u_strd =
                            ps_dec_op->s_disp_frm_buf.u4_y_strd / 2;
            ps_dec_op->s_disp_frm_buf.u4_v_strd =
                            ps_dec_op->s_disp_frm_buf.u4_y_strd / 2;
            ps_dec_op->s_disp_frm_buf.u4_u_wd =
                            ps_dec_op->s_disp_frm_buf.u4_y_wd / 2;
            ps_dec_op->s_disp_frm_buf.u4_v_wd =
                            ps_dec_op->s_disp_frm_buf.u4_y_wd / 2;
            ps_dec_op->s_disp_frm_buf.u4_u_ht =
                            ps_dec_op->s_disp_frm_buf.u4_y_ht / 2;
            ps_dec_op->s_disp_frm_buf.u4_v_ht =
                            ps_dec_op->s_disp_frm_buf.u4_y_ht / 2;
 }

 }
 else if(ps_codec->i4_flush_mode)
 {
        ps_dec_op->u4_error_code = IHEVCD_END_OF_SEQUENCE;
 /* Come out of flush mode */
        ps_codec->i4_flush_mode = 0;
 }

}


void cil_destroy_userrange(struct cil_userrange *userrange)
{
	if (userrange == NULL) {
		return;
	}

	if (userrange->range_str == NULL && userrange->range != NULL) {
		cil_destroy_levelrange(userrange->range);
	}

	free(userrange);
}


static bool perf_addr_filter_match(struct perf_addr_filter *filter,
				     struct file *file, unsigned long offset,
				     unsigned long size)
{
	if (filter->inode != file_inode(file))
		return false;

	if (filter->offset > offset + size)
		return false;

	if (filter->offset + filter->size < offset)
		return false;

	return true;
}


void virtqueue_map_sg(struct iovec *sg, hwaddr *addr,
    size_t num_sg, int is_write)
{
    unsigned int i;
    hwaddr len;

    for (i = 0; i < num_sg; i++) {
        len = sg[i].iov_len;
        sg[i].iov_base = cpu_physical_memory_map(addr[i], &len, is_write);
        if (sg[i].iov_base == NULL || len != sg[i].iov_len) {
            error_report("virtio: trying to map MMIO memory");
            exit(1);
        }
    }
}


static void evhttp_get_body ( struct evhttp_connection * evcon , struct evhttp_request * req ) {
 const char * xfer_enc ;
 if ( req -> kind == EVHTTP_REQUEST && req -> type != EVHTTP_REQ_POST ) {
 evhttp_connection_done ( evcon ) ;
 return ;
 }
 evcon -> state = EVCON_READING_BODY ;
 xfer_enc = evhttp_find_header ( req -> input_headers , "Transfer-Encoding" ) ;
 if ( xfer_enc != NULL && strcasecmp ( xfer_enc , "chunked" ) == 0 ) {
 req -> chunked = 1 ;
 req -> ntoread = - 1 ;
 }
 else {
 if ( evhttp_get_body_length ( req ) == - 1 ) {
 evhttp_connection_fail ( evcon , EVCON_HTTP_INVALID_HEADER ) ;
 return ;
 }
 }
 evhttp_read_body ( evcon , req ) ;
 }


GF_Err gf_isom_add_uuid(GF_ISOFile *movie, u32 trackNumber, bin128 UUID, const u8 *data, u32 data_size)
{
	GF_List *list;
    u32 btype;
	GF_Box *box;
	GF_UnknownUUIDBox *uuidb;

	if (data_size && !data) return GF_BAD_PARAM;
	if (trackNumber==(u32) -1) {
		if (!movie) return GF_BAD_PARAM;
		list = movie->TopBoxes;
	} else if (trackNumber) {
		GF_TrackBox *trak = gf_isom_get_track_from_file(movie, trackNumber);
		if (!trak) return GF_BAD_PARAM;
		if (!trak->child_boxes) trak->child_boxes = gf_list_new();
		list = trak->child_boxes;
	} else {
		if (!movie) return GF_BAD_PARAM;
		if (!movie->moov->child_boxes) movie->moov->child_boxes = gf_list_new();
		list = movie->moov->child_boxes;
	}
    btype = gf_isom_solve_uuid_box((char *) UUID);
    if (!btype) btype = GF_ISOM_BOX_TYPE_UUID;
    box = gf_isom_box_new(btype);
    if (!box) return GF_OUT_OF_MEM;
	uuidb = (GF_UnknownUUIDBox*)box;
	uuidb->internal_4cc = gf_isom_solve_uuid_box((char *) UUID);
	memcpy(uuidb->uuid, UUID, sizeof(bin128));
	uuidb->dataSize = data_size;
	if (data_size) {
		uuidb->data = (char*)gf_malloc(sizeof(char)*data_size);
		if (!uuidb->data) return GF_OUT_OF_MEM;
		memcpy(uuidb->data, data, sizeof(char)*data_size);
	}
	gf_list_add(list, uuidb);
	return GF_OK;
}


bool OobeUI::IsJSReady(const base::Closure& display_is_ready_callback) {
  if (!ready_)
    ready_callbacks_.push_back(display_is_ready_callback);
  return ready_;
}


static void sig_server_looking ( SERVER_REC * server ) {
 g_return_if_fail ( server != NULL ) ;
 printformat ( server , NULL , MSGLEVEL_CLIENTNOTICE , TXT_LOOKING_UP , server -> connrec -> address ) ;
 }


static void file_list_cancel ( NautilusDirectory * directory ) {
 directory_load_cancel ( directory ) ;
 if ( directory -> details -> dequeue_pending_idle_id != 0 ) {
 g_source_remove ( directory -> details -> dequeue_pending_idle_id ) ;
 directory -> details -> dequeue_pending_idle_id = 0 ;
 }
 if ( directory -> details -> pending_file_info != NULL ) {
 g_list_free_full ( directory -> details -> pending_file_info , g_object_unref ) ;
 directory -> details -> pending_file_info = NULL ;
 }
 }


static void _6502_anal_esil_ccall(RAnalOp *op, ut8 data0)
{
	char *flag;
	switch(data0) {
	case 0x10: // bpl $ffff
		flag = "N,!";
		break;
	case 0x30: // bmi $ffff
		flag = "N";
		break;
	case 0x50: // bvc $ffff
		flag = "V,!";
		break;
	case 0x70: // bvs $ffff
		flag = "V";
		break;
	case 0x90: // bcc $ffff
		flag = "C,!";
		break;
	case 0xb0: // bcs $ffff
		flag = "C";
		break;
	case 0xd0: // bne $ffff
		flag = "Z,!";
		break;
	case 0xf0: // beq $ffff
		flag = "Z";
		break;
	default:
		// FIXME: should not happen
		flag = "unk";
		break;
	}
	r_strbuf_setf (&op->esil, "%s,?{,0x%04x,pc,=,}", flag, (op->jump & 0xffff));
}


status_t IPCThreadState::executeCommand(int32_t cmd)
{
 BBinder* obj;
 RefBase::weakref_type* refs;
 status_t result = NO_ERROR;

 switch ((uint32_t)cmd) {
 case BR_ERROR:
        result = mIn.readInt32();
 break;

 case BR_OK:
 break;

 case BR_ACQUIRE:
        refs = (RefBase::weakref_type*)mIn.readPointer();
        obj = (BBinder*)mIn.readPointer();
        ALOG_ASSERT(refs->refBase() == obj,
 "BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
                   refs, obj, refs->refBase());
        obj->incStrong(mProcess.get());
        IF_LOG_REMOTEREFS() {
            LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
            obj->printRefs();
 }
        mOut.writeInt32(BC_ACQUIRE_DONE);
        mOut.writePointer((uintptr_t)refs);
        mOut.writePointer((uintptr_t)obj);
 break;

 case BR_RELEASE:
        refs = (RefBase::weakref_type*)mIn.readPointer();
        obj = (BBinder*)mIn.readPointer();
        ALOG_ASSERT(refs->refBase() == obj,
 "BR_RELEASE: object %p does not match cookie %p (expected %p)",
                   refs, obj, refs->refBase());
        IF_LOG_REMOTEREFS() {
            LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
            obj->printRefs();
 }
        mPendingStrongDerefs.push(obj);
 break;

 case BR_INCREFS:
        refs = (RefBase::weakref_type*)mIn.readPointer();
        obj = (BBinder*)mIn.readPointer();
        refs->incWeak(mProcess.get());
        mOut.writeInt32(BC_INCREFS_DONE);
        mOut.writePointer((uintptr_t)refs);
        mOut.writePointer((uintptr_t)obj);
 break;

 case BR_DECREFS:
        refs = (RefBase::weakref_type*)mIn.readPointer();
        obj = (BBinder*)mIn.readPointer();
        mPendingWeakDerefs.push(refs);
 break;

 case BR_ATTEMPT_ACQUIRE:
        refs = (RefBase::weakref_type*)mIn.readPointer();
        obj = (BBinder*)mIn.readPointer();

 {
 const bool success = refs->attemptIncStrong(mProcess.get());
            ALOG_ASSERT(success && refs->refBase() == obj,
 "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
                       refs, obj, refs->refBase());

            mOut.writeInt32(BC_ACQUIRE_RESULT);
            mOut.writeInt32((int32_t)success);
 }
 break;

 case BR_TRANSACTION:
 {
            binder_transaction_data tr;
            result = mIn.read(&tr, sizeof(tr));
            ALOG_ASSERT(result == NO_ERROR,
 "Not enough command data for brTRANSACTION");
 if (result != NO_ERROR) break;

 Parcel buffer;
            buffer.ipcSetDataReference(
 reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
                tr.data_size,
 reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
                tr.offsets_size/sizeof(binder_size_t), freeBuffer, this);

 const pid_t origPid = mCallingPid;
 const uid_t origUid = mCallingUid;
 const int32_t origStrictModePolicy = mStrictModePolicy;
 const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;

            mCallingPid = tr.sender_pid;
            mCallingUid = tr.sender_euid;
            mLastTransactionBinderFlags = tr.flags;

 int curPrio = getpriority(PRIO_PROCESS, mMyThreadId);
 if (gDisableBackgroundScheduling) {
 if (curPrio > ANDROID_PRIORITY_NORMAL) {
                    setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL);
 }
 } else {
 if (curPrio >= ANDROID_PRIORITY_BACKGROUND) {
                    set_sched_policy(mMyThreadId, SP_BACKGROUND);
 }
 }

 Parcel reply;
 status_t error;
            IF_LOG_TRANSACTIONS() {
 TextOutput::Bundle _b(alog);
                alog << "BR_TRANSACTION thr " << (void*)pthread_self()
 << " / obj " << tr.target.ptr << " / code "
 << TypeCode(tr.code) << ": " << indent << buffer
 << dedent << endl
 << "Data addr = "
 << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
 << ", offsets addr="

                     << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
             }
             if (tr.target.ptr) {
                // We only have a weak reference on the target object, so we must first try to
                // safely acquire a strong reference before doing anything else with it.
                if (reinterpret_cast<RefBase::weakref_type*>(
                        tr.target.ptr)->attemptIncStrong(this)) {
                    error = reinterpret_cast<BBinder*>(tr.cookie)->transact(tr.code, buffer,
                            &reply, tr.flags);
                    reinterpret_cast<BBinder*>(tr.cookie)->decStrong(this);
                } else {
                    error = UNKNOWN_TRANSACTION;
                }

             } else {
                 error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
 }

 if ((tr.flags & TF_ONE_WAY) == 0) {
                LOG_ONEWAY("Sending reply to %d!", mCallingPid);
 if (error < NO_ERROR) reply.setError(error);
                sendReply(reply, 0);
 } else {
                LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
 }

            mCallingPid = origPid;
            mCallingUid = origUid;
            mStrictModePolicy = origStrictModePolicy;
            mLastTransactionBinderFlags = origTransactionBinderFlags;

            IF_LOG_TRANSACTIONS() {
 TextOutput::Bundle _b(alog);
                alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
 << tr.target.ptr << ": " << indent << reply << dedent << endl;
 }

 }
 break;

 case BR_DEAD_BINDER:
 {
 BpBinder *proxy = (BpBinder*)mIn.readPointer();
            proxy->sendObituary();
            mOut.writeInt32(BC_DEAD_BINDER_DONE);
            mOut.writePointer((uintptr_t)proxy);
 } break;

 case BR_CLEAR_DEATH_NOTIFICATION_DONE:
 {
 BpBinder *proxy = (BpBinder*)mIn.readPointer();
            proxy->getWeakRefs()->decWeak(proxy);
 } break;

 case BR_FINISHED:
        result = TIMED_OUT;
 break;

 case BR_NOOP:
 break;

 case BR_SPAWN_LOOPER:
        mProcess->spawnPooledThread(false);
 break;

 default:
        printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
        result = UNKNOWN_ERROR;
 break;
 }

 if (result != NO_ERROR) {
        mLastError = result;
 }

 return result;
}


static int virtnet_poll(struct napi_struct *napi, int budget)
{
	struct receive_queue *rq =
		container_of(napi, struct receive_queue, napi);
	unsigned int r, received;

	received = virtnet_receive(rq, budget);

	/* Out of packets? */
	if (received < budget) {
		r = virtqueue_enable_cb_prepare(rq->vq);
		napi_complete(napi);
		if (unlikely(virtqueue_poll(rq->vq, r)) &&
		    napi_schedule_prep(napi)) {
			virtqueue_disable_cb(rq->vq);
			__napi_schedule(napi);
		}
	}

	return received;
}