OMX_ERRORTYPE  omx_vdec::set_parameter(OMX_IN OMX_HANDLETYPE     hComp,
        OMX_IN OMX_INDEXTYPE paramIndex,
        OMX_IN OMX_PTR        paramData)
{
    OMX_ERRORTYPE eRet = OMX_ErrorNone;
 int ret=0;
 struct v4l2_format fmt;
#ifdef _ANDROID_
 char property_value[PROPERTY_VALUE_MAX] = {0};
#endif
 if (m_state == OMX_StateInvalid) {
        DEBUG_PRINT_ERROR("Set Param in Invalid State");
 return OMX_ErrorInvalidState;
 }
 if (paramData == NULL) {
        DEBUG_PRINT_ERROR("Get Param in Invalid paramData");
 return OMX_ErrorBadParameter;
 }
 if ((m_state != OMX_StateLoaded) &&
            BITMASK_ABSENT(&m_flags,OMX_COMPONENT_OUTPUT_ENABLE_PENDING) &&
 (m_out_bEnabled == OMX_TRUE) &&
            BITMASK_ABSENT(&m_flags, OMX_COMPONENT_INPUT_ENABLE_PENDING) &&
 (m_inp_bEnabled == OMX_TRUE)) {
        DEBUG_PRINT_ERROR("Set Param in Invalid State");
 return OMX_ErrorIncorrectStateOperation;
 }
 switch ((unsigned long)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 (OMX_DirOutput == portDefn->eDir) {
                                   DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition OP port");
 bool port_format_changed = false;
                                   m_display_id = portDefn->format.video.pNativeWindow;
 unsigned int buffer_size;
 /* update output port resolution with client supplied dimensions
                                      in case scaling is enabled, else it follows input resolution set
                                   */
 if (is_down_scalar_enabled) {
                                       DEBUG_PRINT_LOW("SetParam OP: WxH(%u x %u)",
 (unsigned int)portDefn->format.video.nFrameWidth,
 (unsigned int)portDefn->format.video.nFrameHeight);
 if (portDefn->format.video.nFrameHeight != 0x0 &&
                                               portDefn->format.video.nFrameWidth != 0x0) {
                                           memset(&fmt, 0x0, sizeof(struct v4l2_format));
                                           fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
                                           fmt.fmt.pix_mp.pixelformat = capture_capability;
                                           ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_G_FMT, &fmt);
 if (ret) {
                                               DEBUG_PRINT_ERROR("Get Resolution failed");
                                               eRet = OMX_ErrorHardware;
 break;
 }
 if ((portDefn->format.video.nFrameHeight != (unsigned int)fmt.fmt.pix_mp.height) ||
 (portDefn->format.video.nFrameWidth != (unsigned int)fmt.fmt.pix_mp.width)) {
                                                   port_format_changed = true;
 }
                                           update_resolution(portDefn->format.video.nFrameWidth,
                                                   portDefn->format.video.nFrameHeight,
                                                   portDefn->format.video.nFrameWidth,
                                                   portDefn->format.video.nFrameHeight);

 /* set crop info */
                                           rectangle.nLeft = 0;
                                           rectangle.nTop = 0;
                                           rectangle.nWidth = portDefn->format.video.nFrameWidth;
                                           rectangle.nHeight = portDefn->format.video.nFrameHeight;

                                           eRet = is_video_session_supported();
 if (eRet)
 break;
                                           memset(&fmt, 0x0, sizeof(struct v4l2_format));
                                           fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
                                           fmt.fmt.pix_mp.height = drv_ctx.video_resolution.frame_height;
                                           fmt.fmt.pix_mp.width = drv_ctx.video_resolution.frame_width;
                                           fmt.fmt.pix_mp.pixelformat = capture_capability;
                                           DEBUG_PRINT_LOW("fmt.fmt.pix_mp.height = %d , fmt.fmt.pix_mp.width = %d",
                                               fmt.fmt.pix_mp.height, fmt.fmt.pix_mp.width);
                                           ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_FMT, &fmt);
 if (ret) {
                                               DEBUG_PRINT_ERROR("Set Resolution failed");
                                               eRet = OMX_ErrorUnsupportedSetting;
 } else
                                               eRet = get_buffer_req(&drv_ctx.op_buf);
 }

 if (eRet) {
 break;
 }

 if (secure_mode) {
 struct v4l2_control control;
                                           control.id = V4L2_CID_MPEG_VIDC_VIDEO_SECURE_SCALING_THRESHOLD;
 if (ioctl(drv_ctx.video_driver_fd, VIDIOC_G_CTRL, &control) < 0) {
                                               DEBUG_PRINT_ERROR("Failed getting secure scaling threshold : %d, id was : %x", errno, control.id);
                                               eRet = OMX_ErrorHardware;
 } else {
 /* This is a workaround for a bug in fw which uses stride
                                                * and slice instead of width and height to check against
                                                * the threshold.
                                                */
                                               OMX_U32 stride, slice;
 if (drv_ctx.output_format == VDEC_YUV_FORMAT_NV12) {
                                                   stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, portDefn->format.video.nFrameWidth);
                                                   slice = VENUS_Y_SCANLINES(COLOR_FMT_NV12, portDefn->format.video.nFrameHeight);
 } else {
                                                   stride = portDefn->format.video.nFrameWidth;
                                                   slice = portDefn->format.video.nFrameHeight;
 }

                                               DEBUG_PRINT_LOW("Stride is %d, slice is %d, sxs is %d\n", stride, slice, stride * slice);
                                               DEBUG_PRINT_LOW("Threshold value is %d\n", control.value);

 if (stride * slice <= (OMX_U32)control.value) {
                                                   secure_scaling_to_non_secure_opb = true;
                                                   DEBUG_PRINT_HIGH("Enabling secure scalar out of CPZ");
                                                   control.id = V4L2_CID_MPEG_VIDC_VIDEO_NON_SECURE_OUTPUT2;
                                                   control.value = 1;
 if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control) < 0) {
                                                       DEBUG_PRINT_ERROR("Enabling non-secure output2 failed");
                                                       eRet = OMX_ErrorUnsupportedSetting;
 }
 }
 }
 }
 }

 if (eRet) {

                                        break;
                                    }

                                   if (!client_buffers.get_buffer_req(buffer_size)) {
                                        DEBUG_PRINT_ERROR("Error in getting buffer requirements");
                                        eRet = OMX_ErrorBadParameter;
                                    } else if (!port_format_changed) {
                                        if ( portDefn->nBufferCountActual >= drv_ctx.op_buf.mincount &&
                                                portDefn->nBufferSize >=  drv_ctx.op_buf.buffer_size ) {
                                            drv_ctx.op_buf.actualcount = portDefn->nBufferCountActual;
                                           drv_ctx.op_buf.buffer_size = portDefn->nBufferSize;
                                           drv_ctx.extradata_info.count = drv_ctx.op_buf.actualcount;
                                           drv_ctx.extradata_info.size = drv_ctx.extradata_info.count *
                                               drv_ctx.extradata_info.buffer_size;
                                           eRet = set_buffer_req(&drv_ctx.op_buf);
 if (eRet == OMX_ErrorNone)
                                               m_port_def = *portDefn;
 } else {
                                           DEBUG_PRINT_ERROR("ERROR: OP Requirements(#%d: %u) Requested(#%u: %u)",
                                                   drv_ctx.op_buf.mincount, (unsigned int)drv_ctx.op_buf.buffer_size,
 (unsigned int)portDefn->nBufferCountActual, (unsigned int)portDefn->nBufferSize);
                                           eRet = OMX_ErrorBadParameter;
 }
 }
 } else if (OMX_DirInput == portDefn->eDir) {
                                   DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamPortDefinition IP port");
 bool port_format_changed = false;
 if ((portDefn->format.video.xFramerate >> 16) > 0 &&
 (portDefn->format.video.xFramerate >> 16) <= MAX_SUPPORTED_FPS) {
                                       DEBUG_PRINT_HIGH("set_parameter: frame rate set by omx client : %u",
 (unsigned int)portDefn->format.video.xFramerate >> 16);
                                       Q16ToFraction(portDefn->format.video.xFramerate, drv_ctx.frame_rate.fps_numerator,
                                               drv_ctx.frame_rate.fps_denominator);
 if (!drv_ctx.frame_rate.fps_numerator) {
                                           DEBUG_PRINT_ERROR("Numerator is zero setting to 30");
                                           drv_ctx.frame_rate.fps_numerator = 30;
 }
 if (drv_ctx.frame_rate.fps_denominator)
                                           drv_ctx.frame_rate.fps_numerator = (int)
                                               drv_ctx.frame_rate.fps_numerator / drv_ctx.frame_rate.fps_denominator;
                                       drv_ctx.frame_rate.fps_denominator = 1;
                                       frm_int = drv_ctx.frame_rate.fps_denominator * 1e6 /
                                           drv_ctx.frame_rate.fps_numerator;
                                       DEBUG_PRINT_LOW("set_parameter: frm_int(%u) fps(%.2f)",
 (unsigned int)frm_int, drv_ctx.frame_rate.fps_numerator /
 (float)drv_ctx.frame_rate.fps_denominator);

 struct v4l2_outputparm oparm;
 /*XXX: we're providing timing info as seconds per frame rather than frames
                                        * per second.*/
                                       oparm.timeperframe.numerator = drv_ctx.frame_rate.fps_denominator;
                                       oparm.timeperframe.denominator = drv_ctx.frame_rate.fps_numerator;

 struct v4l2_streamparm sparm;
                                       sparm.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
                                       sparm.parm.output = oparm;
 if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_PARM, &sparm)) {
                                           DEBUG_PRINT_ERROR("Unable to convey fps info to driver, performance might be affected");
                                           eRet = OMX_ErrorHardware;
 break;
 }
 }

 if (drv_ctx.video_resolution.frame_height !=
                                           portDefn->format.video.nFrameHeight ||
                                           drv_ctx.video_resolution.frame_width  !=
                                           portDefn->format.video.nFrameWidth) {
                                       DEBUG_PRINT_LOW("SetParam IP: WxH(%u x %u)",
 (unsigned int)portDefn->format.video.nFrameWidth,
 (unsigned int)portDefn->format.video.nFrameHeight);
                                       port_format_changed = true;
                                       OMX_U32 frameWidth = portDefn->format.video.nFrameWidth;
                                       OMX_U32 frameHeight = portDefn->format.video.nFrameHeight;
 if (frameHeight != 0x0 && frameWidth != 0x0) {
 if (m_smoothstreaming_mode &&
 ((frameWidth * frameHeight) <
 (m_smoothstreaming_width * m_smoothstreaming_height))) {
                                               frameWidth = m_smoothstreaming_width;
                                               frameHeight = m_smoothstreaming_height;
                                               DEBUG_PRINT_LOW("NOTE: Setting resolution %u x %u "
 "for adaptive-playback/smooth-streaming",
 (unsigned int)frameWidth, (unsigned int)frameHeight);
 }
                                           update_resolution(frameWidth, frameHeight,
                                                   frameWidth, frameHeight);
                                           eRet = is_video_session_supported();
 if (eRet)
 break;
                                           memset(&fmt, 0x0, sizeof(struct v4l2_format));
                                           fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
                                           fmt.fmt.pix_mp.height = drv_ctx.video_resolution.frame_height;
                                           fmt.fmt.pix_mp.width = drv_ctx.video_resolution.frame_width;
                                           fmt.fmt.pix_mp.pixelformat = output_capability;
                                           DEBUG_PRINT_LOW("fmt.fmt.pix_mp.height = %d , fmt.fmt.pix_mp.width = %d",fmt.fmt.pix_mp.height,fmt.fmt.pix_mp.width);
                                           ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_FMT, &fmt);
 if (ret) {
                                               DEBUG_PRINT_ERROR("Set Resolution failed");
                                               eRet = OMX_ErrorUnsupportedSetting;
 } else {
 if (!is_down_scalar_enabled)
                                               eRet = get_buffer_req(&drv_ctx.op_buf);
 }
 }
 }
 if (m_custom_buffersize.input_buffersize
 && (portDefn->nBufferSize > m_custom_buffersize.input_buffersize)) {
                                       DEBUG_PRINT_ERROR("ERROR: Custom buffer size set by client: %d, trying to set: %d",
                                               m_custom_buffersize.input_buffersize, portDefn->nBufferSize);

                                        eRet = OMX_ErrorBadParameter;
                                        break;
                                    }
                                    if (portDefn->nBufferCountActual >= drv_ctx.ip_buf.mincount
                                            || portDefn->nBufferSize != drv_ctx.ip_buf.buffer_size) {
                                        port_format_changed = true;
                                       vdec_allocatorproperty *buffer_prop = &drv_ctx.ip_buf;
                                       drv_ctx.ip_buf.actualcount = portDefn->nBufferCountActual;
                                       drv_ctx.ip_buf.buffer_size = (portDefn->nBufferSize + buffer_prop->alignment - 1) &
 (~(buffer_prop->alignment - 1));
                                       eRet = set_buffer_req(buffer_prop);
 }
 if (false == port_format_changed) {
                                       DEBUG_PRINT_ERROR("ERROR: IP Requirements(#%d: %u) Requested(#%u: %u)",
                                               drv_ctx.ip_buf.mincount, (unsigned int)drv_ctx.ip_buf.buffer_size,
 (unsigned int)portDefn->nBufferCountActual, (unsigned int)portDefn->nBufferSize);
                                       eRet = OMX_ErrorBadParameter;
 }
 } else if (portDefn->eDir ==  OMX_DirMax) {
                                   DEBUG_PRINT_ERROR(" Set_parameter: Bad Port idx %d",
 (int)portDefn->nPortIndex);
                                   eRet = OMX_ErrorBadPortIndex;
 }
 }
 break;
 case OMX_IndexParamVideoPortFormat: {
                                VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PORTFORMATTYPE);
                                OMX_VIDEO_PARAM_PORTFORMATTYPE *portFmt =
 (OMX_VIDEO_PARAM_PORTFORMATTYPE *)paramData;
 int ret=0;
 struct v4l2_format fmt;
                                DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoPortFormat 0x%x, port: %u",
                                        portFmt->eColorFormat, (unsigned int)portFmt->nPortIndex);

                                memset(&fmt, 0x0, sizeof(struct v4l2_format));
 if (1 == portFmt->nPortIndex) {
                                    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
                                    fmt.fmt.pix_mp.height = drv_ctx.video_resolution.frame_height;
                                    fmt.fmt.pix_mp.width = drv_ctx.video_resolution.frame_width;
                                    fmt.fmt.pix_mp.pixelformat = capture_capability;
 enum vdec_output_fromat op_format;
 if (portFmt->eColorFormat == (OMX_COLOR_FORMATTYPE)
                                                QOMX_COLOR_FORMATYUV420PackedSemiPlanar32m ||
                                            portFmt->eColorFormat == (OMX_COLOR_FORMATTYPE)
                                                QOMX_COLOR_FORMATYUV420PackedSemiPlanar32mMultiView ||
                                            portFmt->eColorFormat == OMX_COLOR_FormatYUV420Planar ||
                                            portFmt->eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar)
                                        op_format = (enum vdec_output_fromat)VDEC_YUV_FORMAT_NV12;
 else
                                        eRet = OMX_ErrorBadParameter;

 if (eRet == OMX_ErrorNone) {
                                        drv_ctx.output_format = op_format;
                                        ret = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_FMT, &fmt);
 if (ret) {
                                            DEBUG_PRINT_ERROR("Set output format failed");
                                            eRet = OMX_ErrorUnsupportedSetting;
 /*TODO: How to handle this case */
 } else {
                                            eRet = get_buffer_req(&drv_ctx.op_buf);
 }
 }
 if (eRet == OMX_ErrorNone) {
 if (!client_buffers.set_color_format(portFmt->eColorFormat)) {
                                            DEBUG_PRINT_ERROR("Set color format failed");
                                            eRet = OMX_ErrorBadParameter;
 }
 }
 }
 }
 break;

 case OMX_QcomIndexPortDefn: {
                            VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_PARAM_PORTDEFINITIONTYPE);
                            OMX_QCOM_PARAM_PORTDEFINITIONTYPE *portFmt =
 (OMX_QCOM_PARAM_PORTDEFINITIONTYPE *) paramData;
                            DEBUG_PRINT_LOW("set_parameter: OMX_IndexQcomParamPortDefinitionType %u",
 (unsigned int)portFmt->nFramePackingFormat);

 /* Input port */
 if (portFmt->nPortIndex == 0) {
 if (portFmt->nFramePackingFormat == OMX_QCOM_FramePacking_Arbitrary) {
 if (secure_mode) {
                                        arbitrary_bytes = false;
                                        DEBUG_PRINT_ERROR("setparameter: cannot set to arbitary bytes mode in secure session");
                                        eRet = OMX_ErrorUnsupportedSetting;
 } else {
                                        arbitrary_bytes = true;
 }
 } else if (portFmt->nFramePackingFormat ==
                                        OMX_QCOM_FramePacking_OnlyOneCompleteFrame) {
                                    arbitrary_bytes = false;
#ifdef _ANDROID_
                                    property_get("vidc.dec.debug.arbitrarybytes.mode", property_value, "0");
 if (atoi(property_value)) {
                                        DEBUG_PRINT_HIGH("arbitrary_bytes enabled via property command");
                                        arbitrary_bytes = true;
 }
#endif
 } else {
                                    DEBUG_PRINT_ERROR("Setparameter: unknown FramePacking format %u",
 (unsigned int)portFmt->nFramePackingFormat);
                                    eRet = OMX_ErrorUnsupportedSetting;
 }
 } else if (portFmt->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) {
                                DEBUG_PRINT_HIGH("set_parameter: OMX_IndexQcomParamPortDefinitionType OP Port");
 if ( (portFmt->nMemRegion > OMX_QCOM_MemRegionInvalid &&
                                            portFmt->nMemRegion < OMX_QCOM_MemRegionMax) &&
                                        portFmt->nCacheAttr == OMX_QCOM_CacheAttrNone) {
                                    m_out_mem_region_smi = OMX_TRUE;
 if ((m_out_mem_region_smi && m_out_pvt_entry_pmem)) {
                                        DEBUG_PRINT_HIGH("set_parameter: OMX_IndexQcomParamPortDefinitionType OP Port: out pmem set");
                                        m_use_output_pmem = OMX_TRUE;
 }
 }
 }
 }
 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(drv_ctx.kind, "OMX.qcom.video.decoder.avc",OMX_MAX_STRINGNAME_SIZE)) {
 if (!strncmp((char*)comp_role->cRole,"video_decoder.avc",OMX_MAX_STRINGNAME_SIZE)) {
                                          strlcpy((char*)m_cRole,"video_decoder.avc",OMX_MAX_STRINGNAME_SIZE);
 } else {
                                          DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole);
                                          eRet =OMX_ErrorUnsupportedSetting;
 }
 } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.mvc", OMX_MAX_STRINGNAME_SIZE)) {
 if (!strncmp((char*)comp_role->cRole, "video_decoder.mvc", OMX_MAX_STRINGNAME_SIZE)) {
                                          strlcpy((char*)m_cRole, "video_decoder.mvc", OMX_MAX_STRINGNAME_SIZE);
 } else {
                                          DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole);
                                          eRet =OMX_ErrorUnsupportedSetting;
 }
 } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) {
 if (!strncmp((const char*)comp_role->cRole,"video_decoder.mpeg4",OMX_MAX_STRINGNAME_SIZE)) {
                                          strlcpy((char*)m_cRole,"video_decoder.mpeg4",OMX_MAX_STRINGNAME_SIZE);
 } else {
                                          DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole);
                                          eRet = OMX_ErrorUnsupportedSetting;
 }
 } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.h263",OMX_MAX_STRINGNAME_SIZE)) {
 if (!strncmp((const char*)comp_role->cRole,"video_decoder.h263",OMX_MAX_STRINGNAME_SIZE)) {
                                          strlcpy((char*)m_cRole,"video_decoder.h263",OMX_MAX_STRINGNAME_SIZE);
 } else {
                                          DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole);
                                          eRet =OMX_ErrorUnsupportedSetting;
 }
 } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.mpeg2",OMX_MAX_STRINGNAME_SIZE)) {
 if (!strncmp((const char*)comp_role->cRole,"video_decoder.mpeg2",OMX_MAX_STRINGNAME_SIZE)) {
                                          strlcpy((char*)m_cRole,"video_decoder.mpeg2",OMX_MAX_STRINGNAME_SIZE);
 } else {
                                          DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole);
                                          eRet = OMX_ErrorUnsupportedSetting;
 }
 } else if ((!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.divx",OMX_MAX_STRINGNAME_SIZE)) ||
 (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.divx311", OMX_MAX_STRINGNAME_SIZE)) ||
 (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.divx4", OMX_MAX_STRINGNAME_SIZE))
 ) {
 if (!strncmp((const char*)comp_role->cRole,"video_decoder.divx",OMX_MAX_STRINGNAME_SIZE)) {
                                          strlcpy((char*)m_cRole,"video_decoder.divx",OMX_MAX_STRINGNAME_SIZE);
 } else {
                                          DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole);
                                          eRet =OMX_ErrorUnsupportedSetting;
 }
 } else if ( (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.vc1",OMX_MAX_STRINGNAME_SIZE)) ||
 (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.wmv",OMX_MAX_STRINGNAME_SIZE))
 ) {
 if (!strncmp((const char*)comp_role->cRole,"video_decoder.vc1",OMX_MAX_STRINGNAME_SIZE)) {
                                          strlcpy((char*)m_cRole,"video_decoder.vc1",OMX_MAX_STRINGNAME_SIZE);
 } else {
                                          DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole);
                                          eRet =OMX_ErrorUnsupportedSetting;
 }
 } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.vp8",OMX_MAX_STRINGNAME_SIZE)) {
 if (!strncmp((const char*)comp_role->cRole,"video_decoder.vp8",OMX_MAX_STRINGNAME_SIZE) ||
 (!strncmp((const char*)comp_role->cRole,"video_decoder.vpx",OMX_MAX_STRINGNAME_SIZE))) {
                                          strlcpy((char*)m_cRole,"video_decoder.vp8",OMX_MAX_STRINGNAME_SIZE);
 } else {
                                          DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole);
                                          eRet = OMX_ErrorUnsupportedSetting;
 }
 } else if (!strncmp(drv_ctx.kind, "OMX.qcom.video.decoder.hevc", OMX_MAX_STRINGNAME_SIZE)) {
 if (!strncmp((const char*)comp_role->cRole, "video_decoder.hevc", OMX_MAX_STRINGNAME_SIZE)) {
                                          strlcpy((char*)m_cRole, "video_decoder.hevc", OMX_MAX_STRINGNAME_SIZE);
 } else {
                                          DEBUG_PRINT_ERROR("Setparameter: unknown Index %s", comp_role->cRole);
                                          eRet = OMX_ErrorUnsupportedSetting;
 }
 } else {
                                      DEBUG_PRINT_ERROR("Setparameter: unknown param %s", drv_ctx.kind);
                                      eRet = OMX_ErrorInvalidComponentName;
 }
 break;
 }

 case OMX_IndexParamPriorityMgmt: {
                             VALIDATE_OMX_PARAM_DATA(paramData, OMX_PRIORITYMGMTTYPE);
 if (m_state != OMX_StateLoaded) {
                                 DEBUG_PRINT_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_priority_mgm.nGroupID = priorityMgmtype->nGroupID;
                             m_priority_mgm.nGroupPriority = priorityMgmtype->nGroupPriority;

 break;
 }

 case OMX_IndexParamCompBufferSupplier: {
                                   VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_BUFFERSUPPLIERTYPE);
                                   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_buffer_supplier.eBufferSupplier = bufferSupplierType->eBufferSupplier;

 else

                                       eRet = OMX_ErrorBadPortIndex;

 break;

 }
 case OMX_IndexParamVideoAvc: {
                             DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoAvc %d",
                                     paramIndex);
 break;
 }
 case (OMX_INDEXTYPE)QOMX_IndexParamVideoMvc: {
                            DEBUG_PRINT_LOW("set_parameter: QOMX_IndexParamVideoMvc %d",
                                     paramIndex);
 break;
 }
 case OMX_IndexParamVideoH263: {
                              DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoH263 %d",
                                      paramIndex);
 break;
 }
 case OMX_IndexParamVideoMpeg4: {
                               DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoMpeg4 %d",
                                       paramIndex);
 break;
 }
 case OMX_IndexParamVideoMpeg2: {
                               DEBUG_PRINT_LOW("set_parameter: OMX_IndexParamVideoMpeg2 %d",
                                       paramIndex);
 break;
 }
 case OMX_QcomIndexParamVideoDecoderPictureOrder: {
                                     VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_DECODER_PICTURE_ORDER);
                                     QOMX_VIDEO_DECODER_PICTURE_ORDER *pictureOrder =
 (QOMX_VIDEO_DECODER_PICTURE_ORDER *)paramData;
 struct v4l2_control control;
 int pic_order,rc=0;
                                     DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamVideoDecoderPictureOrder %d",
                                             pictureOrder->eOutputPictureOrder);
 if (pictureOrder->eOutputPictureOrder == QOMX_VIDEO_DISPLAY_ORDER) {
                                         pic_order = V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DISPLAY;
 } else if (pictureOrder->eOutputPictureOrder == QOMX_VIDEO_DECODE_ORDER) {
                                         pic_order = V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DECODE;
                                         time_stamp_dts.set_timestamp_reorder_mode(false);
 } else
                                         eRet = OMX_ErrorBadParameter;
 if (eRet == OMX_ErrorNone) {
                                         control.id = V4L2_CID_MPEG_VIDC_VIDEO_OUTPUT_ORDER;
                                         control.value = pic_order;
                                         rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control);
 if (rc) {
                                             DEBUG_PRINT_ERROR("Set picture order failed");
                                             eRet = OMX_ErrorUnsupportedSetting;
 }
 }
 break;
 }
 case OMX_QcomIndexParamConcealMBMapExtraData:
                               VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE);
                                     eRet = enable_extradata(VDEC_EXTRADATA_MB_ERROR_MAP, false,
 ((QOMX_ENABLETYPE *)paramData)->bEnable);
 break;
 case OMX_QcomIndexParamFrameInfoExtraData:
                               VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE);
                                       eRet = enable_extradata(OMX_FRAMEINFO_EXTRADATA, false,
 ((QOMX_ENABLETYPE *)paramData)->bEnable);
 break;
 case OMX_ExtraDataFrameDimension:
                               VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE);
                               eRet = enable_extradata(OMX_FRAMEDIMENSION_EXTRADATA, false,
 ((QOMX_ENABLETYPE *)paramData)->bEnable);
 break;
 case OMX_QcomIndexParamInterlaceExtraData:
                               VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE);
                                   eRet = enable_extradata(OMX_INTERLACE_EXTRADATA, false,
 ((QOMX_ENABLETYPE *)paramData)->bEnable);
 break;
 case OMX_QcomIndexParamH264TimeInfo:
                               VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE);
                                   eRet = enable_extradata(OMX_TIMEINFO_EXTRADATA, false,
 ((QOMX_ENABLETYPE *)paramData)->bEnable);
 break;
 case OMX_QcomIndexParamVideoFramePackingExtradata:
                               VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE);
                               eRet = enable_extradata(OMX_FRAMEPACK_EXTRADATA, false,
 ((QOMX_ENABLETYPE *)paramData)->bEnable);
 break;
 case OMX_QcomIndexParamVideoQPExtraData:
                               VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE);
                               eRet = enable_extradata(OMX_QP_EXTRADATA, false,
 ((QOMX_ENABLETYPE *)paramData)->bEnable);
 break;
 case OMX_QcomIndexParamVideoInputBitsInfoExtraData:
                               VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE);
                               eRet = enable_extradata(OMX_BITSINFO_EXTRADATA, false,
 ((QOMX_ENABLETYPE *)paramData)->bEnable);
 break;
 case OMX_QcomIndexEnableExtnUserData:
                               VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE);
                                eRet = enable_extradata(OMX_EXTNUSER_EXTRADATA, false,
 ((QOMX_ENABLETYPE *)paramData)->bEnable);
 break;
 case OMX_QcomIndexParamMpeg2SeqDispExtraData:
                               VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE);
                                eRet = enable_extradata(OMX_MPEG2SEQDISP_EXTRADATA, false,
 ((QOMX_ENABLETYPE *)paramData)->bEnable);
 break;
 case OMX_QcomIndexParamVideoDivx: {
                              QOMX_VIDEO_PARAM_DIVXTYPE* divXType = (QOMX_VIDEO_PARAM_DIVXTYPE *) paramData;
 }
 break;
 case OMX_QcomIndexPlatformPvt: {
                               VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_PLATFORMPRIVATE_EXTN);
                               DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexPlatformPvt OP Port");
                               OMX_QCOM_PLATFORMPRIVATE_EXTN* entryType = (OMX_QCOM_PLATFORMPRIVATE_EXTN *) paramData;
 if (entryType->type != OMX_QCOM_PLATFORM_PRIVATE_PMEM) {
                                   DEBUG_PRINT_HIGH("set_parameter: Platform Private entry type (%d) not supported.", entryType->type);
                                   eRet = OMX_ErrorUnsupportedSetting;
 } else {
                                   m_out_pvt_entry_pmem = OMX_TRUE;
 if ((m_out_mem_region_smi && m_out_pvt_entry_pmem)) {
                                       DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexPlatformPvt OP Port: out pmem set");
                                       m_use_output_pmem = OMX_TRUE;
 }
 }

 }
 break;
 case OMX_QcomIndexParamVideoSyncFrameDecodingMode: {
                                       DEBUG_PRINT_HIGH("set_parameter: OMX_QcomIndexParamVideoSyncFrameDecodingMode");
                                       DEBUG_PRINT_HIGH("set idr only decoding for thumbnail mode");
 struct v4l2_control control;
 int rc;
                                       drv_ctx.idr_only_decoding = 1;
                                       control.id = V4L2_CID_MPEG_VIDC_VIDEO_OUTPUT_ORDER;
                                       control.value = V4L2_MPEG_VIDC_VIDEO_OUTPUT_ORDER_DECODE;
                                       rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control);
 if (rc) {
                                           DEBUG_PRINT_ERROR("Set picture order failed");
                                           eRet = OMX_ErrorUnsupportedSetting;
 } else {
                                           control.id = V4L2_CID_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE;
                                           control.value = V4L2_MPEG_VIDC_VIDEO_SYNC_FRAME_DECODE_ENABLE;
                                           rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control);
 if (rc) {
                                               DEBUG_PRINT_ERROR("Sync frame setting failed");
                                               eRet = OMX_ErrorUnsupportedSetting;
 }
 /*Setting sync frame decoding on driver might change buffer
                                            * requirements so update them here*/
 if (get_buffer_req(&drv_ctx.ip_buf)) {
                                               DEBUG_PRINT_ERROR("Sync frame setting failed: falied to get buffer i/p requirements");
                                               eRet = OMX_ErrorUnsupportedSetting;
 }
 if (get_buffer_req(&drv_ctx.op_buf)) {
                                               DEBUG_PRINT_ERROR("Sync frame setting failed: falied to get buffer o/p requirements");
                                               eRet = OMX_ErrorUnsupportedSetting;
 }
 }
 }
 break;

 case OMX_QcomIndexParamIndexExtraDataType: {
                                    VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXEXTRADATATYPE);
                                       QOMX_INDEXEXTRADATATYPE *extradataIndexType = (QOMX_INDEXEXTRADATATYPE *) paramData;
 if ((extradataIndexType->nIndex == OMX_IndexParamPortDefinition) &&
 (extradataIndexType->bEnabled == OMX_TRUE) &&
 (extradataIndexType->nPortIndex == 1)) {
                                        DEBUG_PRINT_HIGH("set_parameter:  OMX_QcomIndexParamIndexExtraDataType SmoothStreaming");
                                           eRet = enable_extradata(OMX_PORTDEF_EXTRADATA, false, extradataIndexType->bEnabled);

 }
 }
 break;
 case OMX_QcomIndexParamEnableSmoothStreaming: {
#ifndef SMOOTH_STREAMING_DISABLED
                                      eRet = enable_smoothstreaming();
#else
                                      eRet = OMX_ErrorUnsupportedSetting;
#endif
 }
 break;
#if defined (_ANDROID_HONEYCOMB_) || defined (_ANDROID_ICS_)
 /* Need to allow following two set_parameters even in Idle
                                   * state. This is ANDROID architecture which is not in sync
                                   * with openmax standard. */
 case OMX_GoogleAndroidIndexEnableAndroidNativeBuffers: {
                                           VALIDATE_OMX_PARAM_DATA(paramData, EnableAndroidNativeBuffersParams);
 EnableAndroidNativeBuffersParams* enableNativeBuffers = (EnableAndroidNativeBuffersParams *) paramData;
 if (enableNativeBuffers) {
                                               m_enable_android_native_buffers = enableNativeBuffers->enable;
 }
#if !defined(FLEXYUV_SUPPORTED)
 if (m_enable_android_native_buffers) {
 if(!client_buffers.set_color_format(getPreferredColorFormatDefaultMode(0))) {
                                                   DEBUG_PRINT_ERROR("Failed to set native color format!");
                                                   eRet = OMX_ErrorUnsupportedSetting;
 }
 }
#endif
 }
 break;
 case OMX_GoogleAndroidIndexUseAndroidNativeBuffer: {
                                       VALIDATE_OMX_PARAM_DATA(paramData, UseAndroidNativeBufferParams);
                                       eRet = use_android_native_buffer(hComp, paramData);
 }
 break;
#endif
 case OMX_QcomIndexParamEnableTimeStampReorder: {
                                       VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXTIMESTAMPREORDER);
                                       QOMX_INDEXTIMESTAMPREORDER *reorder = (QOMX_INDEXTIMESTAMPREORDER *)paramData;
 if (drv_ctx.picture_order == (vdec_output_order)QOMX_VIDEO_DISPLAY_ORDER) {
 if (reorder->bEnable == OMX_TRUE) {
                                               frm_int =0;
                                               time_stamp_dts.set_timestamp_reorder_mode(true);
 } else
                                               time_stamp_dts.set_timestamp_reorder_mode(false);
 } else {
                                           time_stamp_dts.set_timestamp_reorder_mode(false);
 if (reorder->bEnable == OMX_TRUE) {
                                               eRet = OMX_ErrorUnsupportedSetting;
 }
 }
 }
 break;
 case OMX_IndexParamVideoProfileLevelCurrent: {
                                     VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PROFILELEVELTYPE);
                                     OMX_VIDEO_PARAM_PROFILELEVELTYPE* pParam =
 (OMX_VIDEO_PARAM_PROFILELEVELTYPE*)paramData;
 if (pParam) {
                                         m_profile_lvl.eProfile = pParam->eProfile;
                                         m_profile_lvl.eLevel = pParam->eLevel;
 }
 break;

 }
 case OMX_QcomIndexParamVideoMetaBufferMode:
 {
            VALIDATE_OMX_PARAM_DATA(paramData, StoreMetaDataInBuffersParams);
 StoreMetaDataInBuffersParams *metabuffer =
 (StoreMetaDataInBuffersParams *)paramData;
 if (!metabuffer) {
                DEBUG_PRINT_ERROR("Invalid param: %p", metabuffer);
                eRet = OMX_ErrorBadParameter;
 break;
 }
 if (m_disable_dynamic_buf_mode) {
                DEBUG_PRINT_HIGH("Dynamic buffer mode disabled by setprop");
                eRet = OMX_ErrorUnsupportedSetting;
 break;
 }
 if (metabuffer->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) {
 struct v4l2_control control;
 struct v4l2_format fmt;
                    control.id = V4L2_CID_MPEG_VIDC_VIDEO_ALLOC_MODE_OUTPUT;
 if (metabuffer->bStoreMetaData == true) {
                    control.value = V4L2_MPEG_VIDC_VIDEO_DYNAMIC;
 } else {
                        control.value = V4L2_MPEG_VIDC_VIDEO_STATIC;
 }
 int rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL,&control);
 if (!rc) {
                        DEBUG_PRINT_HIGH("%s buffer mode",
 (metabuffer->bStoreMetaData == true)? "Enabled dynamic" : "Disabled dynamic");
                               dynamic_buf_mode = metabuffer->bStoreMetaData;
 } else {
                        DEBUG_PRINT_ERROR("Failed to %s buffer mode",
 (metabuffer->bStoreMetaData == true)? "enable dynamic" : "disable dynamic");
                        eRet = OMX_ErrorUnsupportedSetting;
 }
 } else {
                    DEBUG_PRINT_ERROR(
 "OMX_QcomIndexParamVideoMetaBufferMode not supported for port: %u",
 (unsigned int)metabuffer->nPortIndex);
                    eRet = OMX_ErrorUnsupportedSetting;
 }
 break;
 }
 case OMX_QcomIndexParamVideoDownScalar:
 {
            VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXDOWNSCALAR);
            QOMX_INDEXDOWNSCALAR* pParam = (QOMX_INDEXDOWNSCALAR*)paramData;
 struct v4l2_control control;
 int rc;
 if (pParam) {
                is_down_scalar_enabled = pParam->bEnable;
 if (is_down_scalar_enabled) {
                    control.id = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_MODE;
                    control.value = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_OUTPUT_SECONDARY;
                    DEBUG_PRINT_LOW("set_parameter:  OMX_QcomIndexParamVideoDownScalar value = %d", pParam->bEnable);
                    rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control);
 if (rc < 0) {
                        DEBUG_PRINT_ERROR("Failed to set down scalar on driver.");
                        eRet = OMX_ErrorUnsupportedSetting;
 }
                    control.id = V4L2_CID_MPEG_VIDC_VIDEO_KEEP_ASPECT_RATIO;
                    control.value = 1;
                    rc = ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control);
 if (rc < 0) {
                        DEBUG_PRINT_ERROR("Failed to set keep aspect ratio on driver.");
                        eRet = OMX_ErrorUnsupportedSetting;
 }
 }
 }
 break;
 }
#ifdef ADAPTIVE_PLAYBACK_SUPPORTED
 case OMX_QcomIndexParamVideoAdaptivePlaybackMode:
 {
            VALIDATE_OMX_PARAM_DATA(paramData, PrepareForAdaptivePlaybackParams);
            DEBUG_PRINT_LOW("set_parameter: OMX_GoogleAndroidIndexPrepareForAdaptivePlayback");
 PrepareForAdaptivePlaybackParams* pParams =
 (PrepareForAdaptivePlaybackParams *) paramData;
 if (pParams->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) {
 if (!pParams->bEnable) {
 return OMX_ErrorNone;
 }
 if (pParams->nMaxFrameWidth > maxSmoothStreamingWidth
 || pParams->nMaxFrameHeight > maxSmoothStreamingHeight) {
                    DEBUG_PRINT_ERROR(
 "Adaptive playback request exceeds max supported resolution : [%u x %u] vs [%u x %u]",
 (unsigned int)pParams->nMaxFrameWidth, (unsigned int)pParams->nMaxFrameHeight,
 (unsigned int)maxSmoothStreamingWidth, (unsigned int)maxSmoothStreamingHeight);
                    eRet = OMX_ErrorBadParameter;
 } else {
                    eRet = enable_adaptive_playback(pParams->nMaxFrameWidth, pParams->nMaxFrameHeight);
 }
 } else {
                DEBUG_PRINT_ERROR(
 "Prepare for adaptive playback supported only on output port");
                eRet = OMX_ErrorBadParameter;
 }
 break;
 }

#endif
 case OMX_QcomIndexParamVideoCustomBufferSize:
 {
            VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_CUSTOM_BUFFERSIZE);
            DEBUG_PRINT_LOW("set_parameter: OMX_QcomIndexParamVideoCustomBufferSize");
            QOMX_VIDEO_CUSTOM_BUFFERSIZE* pParam = (QOMX_VIDEO_CUSTOM_BUFFERSIZE*)paramData;
 if (pParam->nPortIndex == OMX_CORE_INPUT_PORT_INDEX) {
 struct v4l2_control control;
                control.id = V4L2_CID_MPEG_VIDC_VIDEO_BUFFER_SIZE_LIMIT;
                control.value = pParam->nBufferSize;
 if (ioctl(drv_ctx.video_driver_fd, VIDIOC_S_CTRL, &control)) {
                    DEBUG_PRINT_ERROR("Failed to set input buffer size");
                    eRet = OMX_ErrorUnsupportedSetting;
 } else {
                    eRet = get_buffer_req(&drv_ctx.ip_buf);
 if (eRet == OMX_ErrorNone) {
                        m_custom_buffersize.input_buffersize = drv_ctx.ip_buf.buffer_size;
                        DEBUG_PRINT_HIGH("Successfully set custom input buffer size = %d",
                            m_custom_buffersize.input_buffersize);
 } else {
                        DEBUG_PRINT_ERROR("Failed to get buffer requirement");
 }
 }
 } else {
                DEBUG_PRINT_ERROR("ERROR: Custom buffer size in not supported on output port");
                eRet = OMX_ErrorBadParameter;
 }
 break;
 }
 default: {
                 DEBUG_PRINT_ERROR("Setparameter: unknown param %d", paramIndex);
                 eRet = OMX_ErrorUnsupportedIndex;
 }
 }
 if (eRet != OMX_ErrorNone)
        DEBUG_PRINT_ERROR("set_parameter: Error: 0x%x, setting param 0x%x", eRet, paramIndex);
 return eRet;
}


void BTM_SetOutService(BD_ADDR bd_addr, UINT8 service_id, UINT32 mx_chan_id)
{
    tBTM_SEC_DEV_REC *p_dev_rec;
    tBTM_SEC_SERV_REC *p_serv_rec = &btm_cb.sec_serv_rec[0];
 int i;

    btm_cb.p_out_serv = p_serv_rec;
    p_dev_rec = btm_find_dev (bd_addr);

 for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_serv_rec++)
 {
 if ((p_serv_rec->security_flags & BTM_SEC_IN_USE)
 && (p_serv_rec->service_id == service_id)
 && (p_serv_rec->orig_mx_chan_id == mx_chan_id))
 {
            BTM_TRACE_API("BTM_SetOutService p_out_serv id %d, psm 0x%04x, proto_id %d, chan_id %d",
                           p_serv_rec->service_id, p_serv_rec->psm, p_serv_rec->mx_proto_id, p_serv_rec->orig_mx_chan_id);
            btm_cb.p_out_serv = p_serv_rec;
 if (p_dev_rec)
                p_dev_rec->p_cur_service = p_serv_rec;
 break;
 }
 }
}


ex_win_close(
    int		forceit,
    win_T	*win,
    tabpage_T	*tp)		// NULL or the tab page "win" is in
{
    int		need_hide;
    buf_T	*buf = win->w_buffer;

    // Never close the autocommand window.
    if (win == aucmd_win)
    {
	emsg(_(e_cannot_close_autocmd_or_popup_window));
	return;
    }

    need_hide = (bufIsChanged(buf) && buf->b_nwindows <= 1);
    if (need_hide && !buf_hide(buf) && !forceit)
    {
#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
	if ((p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) && p_write)
	{
	    bufref_T bufref;

	    set_bufref(&bufref, buf);
	    dialog_changed(buf, FALSE);
	    if (bufref_valid(&bufref) && bufIsChanged(buf))
		return;
	    need_hide = FALSE;
	}
	else
#endif
	{
	    no_write_message();
	    return;
	}
    }

#ifdef FEAT_GUI
    need_mouse_correct = TRUE;
#endif

    // free buffer when not hiding it or when it's a scratch buffer
    if (tp == NULL)
	win_close(win, !need_hide && !buf_hide(buf));
    else
	win_close_othertab(win, !need_hide && !buf_hide(buf), tp);
}


void RenderFrameImpl::DidStartProvisionalLoad(
    blink::WebDocumentLoader* document_loader) {
  if (!document_loader)
    return;

  TRACE_EVENT2("navigation,benchmark,rail",
               "RenderFrameImpl::didStartProvisionalLoad", "id", routing_id_,
               "url", document_loader->GetUrl().GetString().Utf8());

  NavigationState* navigation_state =
      NavigationState::FromDocumentLoader(document_loader);
  if (!navigation_state->was_initiated_in_this_frame()) {
    for (auto& observer : observers_)
      observer.DidStartNavigation(document_loader->GetUrl(), base::nullopt);
  }

  for (auto& observer : observers_)
    observer.ReadyToCommitNavigation(document_loader);
}


IW_IMPL(int) iw_read_bmp_file(struct iw_context *ctx, struct iw_iodescr *iodescr)
{
	struct iwbmprcontext rctx;
	struct iw_image img;
	int retval = 0;

	iw_zeromem(&rctx,sizeof(struct iwbmprcontext));
	iw_zeromem(&img,sizeof(struct iw_image));

	rctx.ctx = ctx;
	rctx.img = &img;
	rctx.iodescr = iodescr;

	// Start with a default sRGB colorspace. This may be overridden later.
	iw_make_srgb_csdescr_2(&rctx.csdescr);

	rctx.has_fileheader = !iw_get_value(ctx,IW_VAL_BMP_NO_FILEHEADER);
	if(rctx.has_fileheader) {
		if(!iwbmp_read_file_header(&rctx)) goto done;
	}
	if(!iwbmp_read_info_header(&rctx)) goto done;

	iwbmp_set_default_bitfields(&rctx);
	if(rctx.bitfields_nbytes>0) {
		if(!iwbmp_read_bitfields(&rctx)) goto done;
	}

	if(rctx.palette_entries>0) {
		if(!iwbmp_read_palette(&rctx)) goto done;
	}
	if(!iwbmp_read_bits(&rctx)) goto done;

	iw_set_input_image(ctx, &img);

	iwbmpr_misc_config(ctx, &rctx);

	retval = 1;
done:
	if(!retval) {
		iw_set_error(ctx,"BMP read failed");
		// If we didn't call iw_set_input_image, 'img' still belongs to us,
		// so free its contents.
		iw_free(ctx, img.pixels);
	}
	return retval;
}


static void tcp_undo_cwr(struct sock *sk, const bool undo_ssthresh)
{
	struct tcp_sock *tp = tcp_sk(sk);

	if (tp->prior_ssthresh) {
		const struct inet_connection_sock *icsk = inet_csk(sk);

		if (icsk->icsk_ca_ops->undo_cwnd)
			tp->snd_cwnd = icsk->icsk_ca_ops->undo_cwnd(sk);
		else
			tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh << 1);

		if (undo_ssthresh && tp->prior_ssthresh > tp->snd_ssthresh) {
			tp->snd_ssthresh = tp->prior_ssthresh;
			TCP_ECN_withdraw_cwr(tp);
		}
	} else {
		tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh);
	}
	tp->snd_cwnd_stamp = tcp_time_stamp;
}


void ByteCodeGenerator::EnsureSpecialScopeSlots(FuncInfo* funcInfo, Scope* scope)
{
    if (scope->GetIsObject())
    {
        if (funcInfo->isThisLexicallyCaptured)
        {
            funcInfo->EnsureThisScopeSlot();
        }

        if (((!funcInfo->IsLambda() && funcInfo->GetCallsEval())
            || funcInfo->isSuperLexicallyCaptured))
        {
            if (funcInfo->superRegister != Js::Constants::NoRegister)
            {
                funcInfo->EnsureSuperScopeSlot();
            }

            if (funcInfo->superCtorRegister != Js::Constants::NoRegister)
            {
                funcInfo->EnsureSuperCtorScopeSlot();
            }
        }

        if (funcInfo->isNewTargetLexicallyCaptured)
        {
            funcInfo->EnsureNewTargetScopeSlot();
        }
    }
    else
    {
        // Don't rely on the Emit() pass to assign scope slots where needed, because peeps/shortcuts
        // may cause some expressions not to be emitted. Assign the slots we need before we start
        // emitting the prolog.
        // TODO: Investigate moving detection of non-local references to Emit() so we don't assign
        // slots to symbols that are never referenced in emitted code.

        if (funcInfo->isThisLexicallyCaptured)
        {
            funcInfo->EnsureThisScopeSlot();
        }

        if (funcInfo->isSuperLexicallyCaptured)
        {
            funcInfo->EnsureSuperScopeSlot();
        }

        if (funcInfo->isSuperCtorLexicallyCaptured)
        {
            funcInfo->EnsureSuperCtorScopeSlot();
        }

        if (funcInfo->isNewTargetLexicallyCaptured)
        {
            funcInfo->EnsureNewTargetScopeSlot();
        }
    }
}


void reclaim_file(DOS_FS * fs)
{
    DOS_FILE orphan;
    int reclaimed, files;
    int changed = 0;
    uint32_t i, next, walk;
    uint32_t *num_refs = NULL;	/* Only for orphaned clusters */
    uint32_t total_num_clusters;

    if (verbose)
	printf("Reclaiming unconnected clusters.\n");

    total_num_clusters = fs->clusters + 2UL;
    num_refs = alloc(total_num_clusters * sizeof(uint32_t));
    memset(num_refs, 0, (total_num_clusters * sizeof(uint32_t)));

    /* Guarantee that all orphan chains (except cycles) end cleanly
     * with an end-of-chain mark.
     */

    for (i = 2; i < total_num_clusters; i++) {
	FAT_ENTRY curEntry;
	get_fat(&curEntry, fs->fat, i, fs);

	next = curEntry.value;
	if (!get_owner(fs, i) && next && next < fs->clusters + 2) {
	    /* Cluster is linked, but not owned (orphan) */
	    FAT_ENTRY nextEntry;
	    get_fat(&nextEntry, fs->fat, next, fs);

	    /* Mark it end-of-chain if it links into an owned cluster,
	     * a free cluster, or a bad cluster.
	     */
	    if (get_owner(fs, next) || !nextEntry.value ||
		FAT_IS_BAD(fs, nextEntry.value))
		set_fat(fs, i, -1);
	    else
		num_refs[next]++;
	}
    }

    /* Scan until all the orphans are accounted for,
     * and all cycles and cross-links are broken
     */
    do {
	tag_free(fs, &orphan, num_refs, changed);
	changed = 0;

	/* Any unaccounted-for orphans must be part of a cycle */
	for (i = 2; i < total_num_clusters; i++) {
	    FAT_ENTRY curEntry;
	    get_fat(&curEntry, fs->fat, i, fs);

	    if (curEntry.value && !FAT_IS_BAD(fs, curEntry.value) &&
		!get_owner(fs, i)) {
		if (!num_refs[curEntry.value]--)
		    die("Internal error: num_refs going below zero");
		set_fat(fs, i, -1);
		changed = curEntry.value;
		printf("Broke cycle at cluster %lu in free chain.\n", (unsigned long)i);

		/* If we've created a new chain head,
		 * tag_free() can claim it
		 */
		if (num_refs[curEntry.value] == 0)
		    break;
	    }
	}
    }
    while (changed);

    /* Now we can start recovery */
    files = reclaimed = 0;
    for (i = 2; i < total_num_clusters; i++)
	/* If this cluster is the head of an orphan chain... */
	if (get_owner(fs, i) == &orphan && !num_refs[i]) {
	    DIR_ENT de;
	    loff_t offset;
	    files++;
	    offset = alloc_rootdir_entry(fs, &de, "FSCK%04dREC");
	    de.start = htole16(i & 0xffff);
	    if (fs->fat_bits == 32)
		de.starthi = htole16(i >> 16);
	    for (walk = i; walk > 0 && walk != -1;
		 walk = next_cluster(fs, walk)) {
		de.size = htole32(le32toh(de.size) + fs->cluster_size);
		reclaimed++;
	    }
	    fs_write(offset, sizeof(DIR_ENT), &de);
	}
    if (reclaimed)
	printf("Reclaimed %d unused cluster%s (%llu bytes) in %d chain%s.\n",
	       reclaimed, reclaimed == 1 ? "" : "s",
	       (unsigned long long)reclaimed * fs->cluster_size, files,
	       files == 1 ? "" : "s");

    free(num_refs);
}


 virtual status_t getProvisionRequest(String8 const &certType,
 String8 const &certAuthority,
 Vector<uint8_t> &request,
 String8 &defaultUrl) {
 Parcel data, reply;
        data.writeInterfaceToken(IDrm::getInterfaceDescriptor());

        data.writeString8(certType);
        data.writeString8(certAuthority);
 status_t status = remote()->transact(GET_PROVISION_REQUEST, data, &reply);
 if (status != OK) {
 return status;
 }

        readVector(reply, request);
        defaultUrl = reply.readString8();

 return reply.readInt32();
 }


static Variant HHVM_METHOD(SimpleXMLIterator, next) {
  auto data = Native::data<SimpleXMLIterator>(this_);
  php_sxe_move_forward_iterator(data);
  return init_null();
}


TEST_F ( FullscreenControllerStateUnitTest , TransitionsForEachState ) {
 AddTab ( browser ( ) , GURL ( url : : kAboutBlankURL ) ) ;
 TestTransitionsForEachState ( ) ;
 }


static int __get_data_block(struct inode *inode, sector_t iblock,
			struct buffer_head *bh, int create, int flag,
			pgoff_t *next_pgofs)
{
	struct f2fs_map_blocks map;
	int err;

	map.m_lblk = iblock;
	map.m_len = bh->b_size >> inode->i_blkbits;
	map.m_next_pgofs = next_pgofs;

	err = f2fs_map_blocks(inode, &map, create, flag);
	if (!err) {
		map_bh(bh, inode->i_sb, map.m_pblk);
		bh->b_state = (bh->b_state & ~F2FS_MAP_FLAGS) | map.m_flags;
		bh->b_size = map.m_len << inode->i_blkbits;
	}
	return err;
}


static void i40e_pci_error_reset_done(struct pci_dev *pdev)
{
	struct i40e_pf *pf = pci_get_drvdata(pdev);

	i40e_reset_and_rebuild(pf, false, false);
}


iasecc_init_gemalto(struct sc_card *card)
{
	struct sc_context *ctx = card->ctx;
	struct sc_path path;
	unsigned int flags;
	int rv = 0;

	LOG_FUNC_CALLED(ctx);

	flags = IASECC_CARD_DEFAULT_FLAGS;

	_sc_card_add_rsa_alg(card, 1024, flags, 0x10001);
	_sc_card_add_rsa_alg(card, 2048, flags, 0x10001);

	card->caps = SC_CARD_CAP_RNG;
	card->caps |= SC_CARD_CAP_APDU_EXT;
	card->caps |= SC_CARD_CAP_USE_FCI_AC;

	sc_format_path("3F00", &path);
	rv = sc_select_file(card, &path, NULL);
	/* Result ignored*/

	rv = iasecc_parse_ef_atr(card);
	sc_log(ctx, "rv %i", rv);
	if (rv == SC_ERROR_FILE_NOT_FOUND)   {
		sc_log(ctx, "Select MF");
		rv = iasecc_select_mf(card, NULL);
		sc_log(ctx, "rv %i", rv);
		LOG_TEST_RET(ctx, rv, "MF selection error");

		rv = iasecc_parse_ef_atr(card);
		sc_log(ctx, "rv %i", rv);
	}
	sc_log(ctx, "rv %i", rv);
	LOG_TEST_RET(ctx, rv, "Cannot read/parse EF.ATR");

	LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}


void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) {
bool Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) {
   assert(pCluster);
   assert(pCluster->m_index < 0);
   assert(idx >= m_clusterCount);

 const long count = m_clusterCount + m_clusterPreloadCount;

 long& size = m_clusterSize;
  assert(size >= count);

   if (count >= size) {
     const long n = (size <= 0) ? 2048 : 2 * size;

    Cluster** const qq = new (std::nothrow) Cluster*[n];
    if (qq == NULL)
      return false;
     Cluster** q = qq;

     Cluster** p = m_clusters;
 Cluster** const pp = p + count;

 while (p != pp)
 *q++ = *p++;

 delete[] m_clusters;

    m_clusters = qq;
    size = n;
 }

  assert(m_clusters);

 Cluster** const p = m_clusters + idx;

 Cluster** q = m_clusters + count;
  assert(q >= p);
  assert(q < (m_clusters + size));

 while (q > p) {
 Cluster** const qq = q - 1;
    assert((*qq)->m_index < 0);

 *q = *qq;
    q = qq;
 }

   m_clusters[idx] = pCluster;
   ++m_clusterPreloadCount;
  return true;
 }


static char * getFunctionName (RCore *core, ut64 off, const char *name, bool prefix) {
	const char *fcnpfx = "";
	if (prefix) {
		if (fcnNeedsPrefix (name) && (!fcnpfx || !*fcnpfx)) {
			fcnpfx = "fcn";
		} else {
			fcnpfx = r_config_get (core->config, "anal.fcnprefix");
		}
	}
	if (r_reg_get (core->anal->reg, name, -1)) {
		return r_str_newf ("%s.%08"PFMT64x, "fcn", off);
	}
	return strdup (name); // r_str_newf ("%s%s%s", fcnpfx, *fcnpfx? ".": "", name);
}


static ssize_t f_hid_opts_report_desc_store(struct config_item *item,
					    const char *page, size_t len)
{
	struct f_hid_opts *opts = to_f_hid_opts(item);
	int ret = -EBUSY;
	char *d;

	mutex_lock(&opts->lock);

	if (opts->refcnt)
		goto end;
	if (len > PAGE_SIZE) {
		ret = -ENOSPC;
		goto end;
	}
	d = kmemdup(page, len, GFP_KERNEL);
	if (!d) {
		ret = -ENOMEM;
		goto end;
	}
	kfree(opts->report_desc);
	opts->report_desc = d;
	opts->report_desc_length = len;
	opts->report_desc_alloc = true;
	ret = len;
end:
	mutex_unlock(&opts->lock);
	return ret;
}


GAppInfo * nautilus_mime_get_default_application_for_file ( NautilusFile * file ) {
 GAppInfo * app ;
 char * mime_type ;
 char * uri_scheme ;
 if ( ! nautilus_mime_actions_check_if_required_attributes_ready ( file ) ) {
 return NULL ;
 }
 mime_type = nautilus_file_get_mime_type ( file ) ;
 app = g_app_info_get_default_for_type ( mime_type , ! nautilus_file_is_local_or_fuse ( file ) ) ;
 g_free ( mime_type ) ;
 if ( app == NULL ) {
 uri_scheme = nautilus_file_get_uri_scheme ( file ) ;
 if ( uri_scheme != NULL ) {
 app = g_app_info_get_default_for_uri_scheme ( uri_scheme ) ;
 g_free ( uri_scheme ) ;
 }
 }
 return app ;
 }


void RenderFrameImpl::DidObserveLazyLoadBehavior(
    WebLocalFrameClient::LazyLoadBehavior lazy_load_behavior) {
  for (auto& observer : observers_)
    observer.DidObserveLazyLoadBehavior(lazy_load_behavior);
}


static struct inode * get_pipe_inode(void)
{
	struct inode *inode = new_inode_pseudo(pipe_mnt->mnt_sb);
	struct pipe_inode_info *pipe;

	if (!inode)
		goto fail_inode;

	inode->i_ino = get_next_ino();

	pipe = alloc_pipe_info();
	if (!pipe)
		goto fail_iput;

	inode->i_pipe = pipe;
	pipe->files = 2;
	pipe->readers = pipe->writers = 1;
	inode->i_fop = &pipefifo_fops;

	/*
	 * Mark the inode dirty from the very beginning,
	 * that way it will never be moved to the dirty
	 * list because "mark_inode_dirty()" will think
	 * that it already _is_ on the dirty list.
	 */
	inode->i_state = I_DIRTY;
	inode->i_mode = S_IFIFO | S_IRUSR | S_IWUSR;
	inode->i_uid = current_fsuid();
	inode->i_gid = current_fsgid();
	inode->i_atime = inode->i_mtime = inode->i_ctime = current_time(inode);

	return inode;

fail_iput:
	iput(inode);

fail_inode:
	return NULL;
}


ObjectData* ObjectData::clone() {
  if (isCppBuiltin()) {
    assertx(!m_cls->hasMemoSlots());
    if (isCollection()) return collections::clone(this);
    if (instanceof(c_Closure::classof())) {
      return c_Closure::fromObject(this)->clone();
    }
    assertx(instanceof(c_Awaitable::classof()));
    // cloning WaitHandles is not allowed
    // invoke the instanceCtor to get the right sort of exception
    auto const ctor = m_cls->instanceCtor();
    ctor(m_cls);
    always_assert(false);
  }

  // clone prevents a leak if something throws before clone() returns
  Object clone;
  auto const nProps = m_cls->numDeclProperties();
  if (hasNativeData()) {
    assertx(m_cls->instanceDtor() == Native::nativeDataInstanceDtor);
    clone = Object::attach(
      Native::nativeDataInstanceCopyCtor(this, m_cls, nProps)
    );
    assertx(clone->hasExactlyOneRef());
    assertx(clone->hasInstanceDtor());
  } else {
    auto const alloc = allocMemoInit(m_cls);

    auto const obj = new (NotNull{}, alloc.mem)
                     ObjectData(m_cls, InitRaw{}, alloc.flags);
    clone = Object::attach(obj);
    assertx(clone->hasExactlyOneRef());
    assertx(!clone->hasInstanceDtor());
  }

  auto const cloneProps = clone->props();
  cloneProps->init(m_cls->numDeclProperties());
  for (auto slot = Slot{0}; slot < nProps; slot++) {
    auto index = m_cls->propSlotToIndex(slot);
    tvDup(*props()->at(index), cloneProps->at(index));
    assertx(assertTypeHint(cloneProps->at(index), slot));
  }

  if (UNLIKELY(getAttribute(HasDynPropArr))) {
    clone->setAttribute(HasDynPropArr);
    g_context->dynPropTable.emplace(clone.get(), dynPropArray().get());
  }
  if (m_cls->rtAttribute(Class::HasClone)) {
    assertx(!isCppBuiltin());
    auto const method = clone->m_cls->lookupMethod(s_clone.get());
    assertx(method);
    clone->unlockObject();
    SCOPE_EXIT { clone->lockObject(); };
    g_context->invokeMethodV(clone.get(), method, InvokeArgs{}, false);
  }
  return clone.detach();
}


ves_icall_Remoting_RealProxy_InternalGetProxyType (MonoTransparentProxy *tp)
{
	return mono_type_get_object (mono_object_domain (tp), &tp->remote_class->proxy_class->byval_arg);
}


std::string ContextualSearchFieldTrial::GetParam(const std::string& name) {
  return variations::GetVariationParamValue(kContextualSearchFieldTrialName,
                                            name);
}


static ssize_t tlbflush_write_file(struct file *file,
		 const char __user *user_buf, size_t count, loff_t *ppos)
{
	char buf[32];
	ssize_t len;
	int ceiling;

	len = min(count, sizeof(buf) - 1);
	if (copy_from_user(buf, user_buf, len))
		return -EFAULT;

	buf[len] = '\0';
	if (kstrtoint(buf, 0, &ceiling))
		return -EINVAL;

	if (ceiling < 0)
		return -EINVAL;

	tlb_single_page_flush_ceiling = ceiling;
	return count;
}


bool BluetoothDeviceChromeOS::IsPaired() const {
  BluetoothDeviceClient::Properties* properties =
      DBusThreadManager::Get()->GetBluetoothDeviceClient()->
          GetProperties(object_path_);
  DCHECK(properties);

  return properties->paired.value() || properties->trusted.value();
}


void MetricsWebContentsObserver::AddTestingObserver(TestingObserver* observer) {
  if (!testing_observers_.HasObserver(observer))
    testing_observers_.AddObserver(observer);
}


  static Status TransposeOperand(OpKernelContext* ctx, const Tensor& input,
                                 const std::vector<int>& permutation,
                                 Tensor* output) {
    if (!ShouldTranspose(input.shape(), permutation)) {
      return CopyFrom(input, input.shape(), output);
    }
    TensorShape transposed_shape;
    for (int i = 0; i < input.dims(); ++i) {
      transposed_shape.AddDim(input.dim_size(permutation[i]));
    }
    // For empty Tensors, just change the shape. E.g. we may need to transpose
    // from shape [1, 0, 5] to [5, 1, 0].
    if (input.NumElements() == 0) {
      return CopyFrom(input, transposed_shape, output);
    }
    TF_RETURN_IF_ERROR(
        ctx->allocate_temp(DataTypeToEnum<T>::value, transposed_shape, output));
    const Device& device = ctx->eigen_device<Device>();
    TF_RETURN_IF_ERROR(DoTranspose(device, input, permutation, output));
    return Status::OK();
  }


net::URLRequestContextGetter* DownloadManagerImpl::GetURLRequestContextGetter(
    const download::DownloadCreateInfo& info) {
  StoragePartition* storage_partition = GetStoragePartition(
      browser_context_, info.render_process_id, info.render_frame_id);
  return storage_partition ? storage_partition->GetURLRequestContext()
                           : nullptr;
}


static inline int sctp_phashfn(struct net *net, __u16 lport)
{
	return (net_hash_mix(net) + lport) & (sctp_port_hashsize - 1);
}


void WebFrameLoaderClient::dispatchWillSendRequest(
    DocumentLoader* loader, unsigned long identifier, ResourceRequest& request,
    const ResourceResponse& redirect_response) {

  if (loader) {
    request.setTargetType(DetermineTargetTypeFromLoader(loader));
  }

  if (request.url().isEmpty())
    request.setURL(KURL(ParsedURLString, "about:blank"));
  if (request.firstPartyForCookies().isEmpty())
    request.setFirstPartyForCookies(KURL(ParsedURLString, "about:blank"));

  if (webframe_->client()) {
    WrappedResourceRequest webreq(request);
    WrappedResourceResponse webresp(redirect_response);
    webframe_->client()->willSendRequest(
        webframe_, identifier, webreq, webresp);
  }
}


void BaseRenderingContext2D::Reset() {
  ValidateStateStack();
  UnwindStateStack();
  state_stack_.resize(1);
  state_stack_.front() = CanvasRenderingContext2DState::Create();
  path_.Clear();
  if (PaintCanvas* c = ExistingDrawingCanvas()) {
    DCHECK_EQ(c->getSaveCount(), 2);
    c->restore();
    c->save();
    DCHECK(c->getTotalMatrix().isIdentity());
#if DCHECK_IS_ON()
    SkIRect clip_bounds;
    DCHECK(c->getDeviceClipBounds(&clip_bounds));
    DCHECK(clip_bounds == c->imageInfo().bounds());
 #endif
   }
   ValidateStateStack();
  origin_tainted_by_content_ = false;
 }


PHP_METHOD(Phar, delMetadata)
{
	char *error;

	PHAR_ARCHIVE_OBJECT();

	if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
		zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Write operations disabled by the php.ini setting phar.readonly");
		return;
	}

	if (phar_obj->arc.archive->metadata) {
		zval_ptr_dtor(&phar_obj->arc.archive->metadata);
		phar_obj->arc.archive->metadata = NULL;
		phar_obj->arc.archive->is_modified = 1;
		phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);

		if (error) {
			zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
			efree(error);
			RETURN_FALSE;
		} else {
			RETURN_TRUE;
		}

	} else {
		RETURN_TRUE;
	}
}


AP4_AtomMetaDataValue::ToBytes(AP4_DataBuffer& bytes) const
{
    return m_DataAtom->LoadBytes(bytes);
}


int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out,
                   unsigned int flags)
{
    BIO *cont;
    int r;
    if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_id_smime_ct_compressedData) {
        CMSerr(CMS_F_CMS_UNCOMPRESS, CMS_R_TYPE_NOT_COMPRESSED_DATA);
        return 0;
    }

    if (!dcont && !check_content(cms))
        return 0;

    cont = CMS_dataInit(cms, dcont);
    if (!cont)
        return 0;
    r = cms_copy_content(out, cont, flags);
    do_free_upto(cont, dcont);
    return r;
}


u_savesub(linenr_T lnum)
{
    if (undo_off)
	return OK;

    return (u_savecommon(lnum - 1, lnum + 1, lnum + 1, FALSE));
}


FormAssociatedElement::FormAssociatedElement()
    : m_form(0)
{
}


static enum TIFFReadDirEntryErr TIFFReadDirEntryIfd8Array(TIFF* tif, TIFFDirEntry* direntry, uint64** value)
{
	enum TIFFReadDirEntryErr err;
	uint32 count;
	void* origdata;
	uint64* data;
	switch (direntry->tdir_type)
	{
		case TIFF_LONG:
		case TIFF_LONG8:
		case TIFF_IFD:
		case TIFF_IFD8:
			break;
		default:
			return(TIFFReadDirEntryErrType);
	}
	err=TIFFReadDirEntryArray(tif,direntry,&count,8,&origdata);
	if ((err!=TIFFReadDirEntryErrOk)||(origdata==0))
	{
		*value=0;
		return(err);
	}
	switch (direntry->tdir_type)
	{
		case TIFF_LONG8:
		case TIFF_IFD8:
			*value=(uint64*)origdata;
			if (tif->tif_flags&TIFF_SWAB)
				TIFFSwabArrayOfLong8(*value,count);
			return(TIFFReadDirEntryErrOk);
	}
	data=(uint64*)_TIFFmalloc(count*8);
	if (data==0)
	{
		_TIFFfree(origdata);
		return(TIFFReadDirEntryErrAlloc);
	}
	switch (direntry->tdir_type)
	{
		case TIFF_LONG:
		case TIFF_IFD:
			{
				uint32* ma;
				uint64* mb;
				uint32 n;
				ma=(uint32*)origdata;
				mb=data;
				for (n=0; n<count; n++)
				{
					if (tif->tif_flags&TIFF_SWAB)
						TIFFSwabLong(ma);
					*mb++=(uint64)(*ma++);
				}
			}
			break;
	}
	_TIFFfree(origdata);
	*value=data;
	return(TIFFReadDirEntryErrOk);
}


static cmsBool Type_LUTB2A_Write ( struct _cms_typehandler_struct * self , cmsIOHANDLER * io , void * Ptr , cmsUInt32Number nItems ) {
 cmsPipeline * Lut = ( cmsPipeline * ) Ptr ;
 int inputChan , outputChan ;
 cmsStage * A = NULL , * B = NULL , * M = NULL ;
 cmsStage * Matrix = NULL ;
 cmsStage * CLUT = NULL ;
 cmsUInt32Number offsetB = 0 , offsetMat = 0 , offsetM = 0 , offsetC = 0 , offsetA = 0 ;
 cmsUInt32Number BaseOffset , DirectoryPos , CurrentPos ;
 BaseOffset = io -> Tell ( io ) - sizeof ( _cmsTagBase ) ;
 if ( ! cmsPipelineCheckAndRetreiveStages ( Lut , 1 , cmsSigCurveSetElemType , & B ) ) if ( ! cmsPipelineCheckAndRetreiveStages ( Lut , 3 , cmsSigCurveSetElemType , cmsSigMatrixElemType , cmsSigCurveSetElemType , & B , & Matrix , & M ) ) if ( ! cmsPipelineCheckAndRetreiveStages ( Lut , 3 , cmsSigCurveSetElemType , cmsSigCLutElemType , cmsSigCurveSetElemType , & B , & CLUT , & A ) ) if ( ! cmsPipelineCheckAndRetreiveStages ( Lut , 5 , cmsSigCurveSetElemType , cmsSigMatrixElemType , cmsSigCurveSetElemType , cmsSigCLutElemType , cmsSigCurveSetElemType , & B , & Matrix , & M , & CLUT , & A ) ) {
 cmsSignalError ( self -> ContextID , cmsERROR_NOT_SUITABLE , "LUT is not suitable to be saved as LutBToA" ) ;
 return FALSE ;
 }
 inputChan = cmsPipelineInputChannels ( Lut ) ;
 outputChan = cmsPipelineOutputChannels ( Lut ) ;
 if ( ! _cmsWriteUInt8Number ( io , ( cmsUInt8Number ) inputChan ) ) return FALSE ;
 if ( ! _cmsWriteUInt8Number ( io , ( cmsUInt8Number ) outputChan ) ) return FALSE ;
 if ( ! _cmsWriteUInt16Number ( io , 0 ) ) return FALSE ;
 DirectoryPos = io -> Tell ( io ) ;
 if ( ! _cmsWriteUInt32Number ( io , 0 ) ) return FALSE ;
 if ( ! _cmsWriteUInt32Number ( io , 0 ) ) return FALSE ;
 if ( ! _cmsWriteUInt32Number ( io , 0 ) ) return FALSE ;
 if ( ! _cmsWriteUInt32Number ( io , 0 ) ) return FALSE ;
 if ( ! _cmsWriteUInt32Number ( io , 0 ) ) return FALSE ;
 if ( A != NULL ) {
 offsetA = io -> Tell ( io ) - BaseOffset ;
 if ( ! WriteSetOfCurves ( self , io , cmsSigParametricCurveType , A ) ) return FALSE ;
 }
 if ( CLUT != NULL ) {
 offsetC = io -> Tell ( io ) - BaseOffset ;
 if ( ! WriteCLUT ( self , io , Lut -> SaveAs8Bits ? 1 : 2 , CLUT ) ) return FALSE ;
 }
 if ( M != NULL ) {
 offsetM = io -> Tell ( io ) - BaseOffset ;
 if ( ! WriteSetOfCurves ( self , io , cmsSigParametricCurveType , M ) ) return FALSE ;
 }
 if ( Matrix != NULL ) {
 offsetMat = io -> Tell ( io ) - BaseOffset ;
 if ( ! WriteMatrix ( self , io , Matrix ) ) return FALSE ;
 }
 if ( B != NULL ) {
 offsetB = io -> Tell ( io ) - BaseOffset ;
 if ( ! WriteSetOfCurves ( self , io , cmsSigParametricCurveType , B ) ) return FALSE ;
 }
 CurrentPos = io -> Tell ( io ) ;
 if ( ! io -> Seek ( io , DirectoryPos ) ) return FALSE ;
 if ( ! _cmsWriteUInt32Number ( io , offsetB ) ) return FALSE ;
 if ( ! _cmsWriteUInt32Number ( io , offsetMat ) ) return FALSE ;
 if ( ! _cmsWriteUInt32Number ( io , offsetM ) ) return FALSE ;
 if ( ! _cmsWriteUInt32Number ( io , offsetC ) ) return FALSE ;
 if ( ! _cmsWriteUInt32Number ( io , offsetA ) ) return FALSE ;
 if ( ! io -> Seek ( io , CurrentPos ) ) return FALSE ;
 return TRUE ;
 cmsUNUSED_PARAMETER ( nItems ) ;
 }


int32_t PepperFlashRendererHost::OnGetProxyForURL(
    ppapi::host::HostMessageContext* host_context,
    const std::string& url) {
  GURL gurl(url);
  if (!gurl.is_valid())
    return PP_ERROR_FAILED;
  std::string proxy;
  bool result = content::RenderThread::Get()->ResolveProxy(gurl, &proxy);
  if (!result)
    return PP_ERROR_FAILED;
  host_context->reply_msg = PpapiPluginMsg_Flash_GetProxyForURLReply(proxy);
  return PP_OK;
}


vhost_scsi_do_plug(struct vhost_scsi_tpg *tpg,
		  struct se_lun *lun, bool plug)
{

	struct vhost_scsi *vs = tpg->vhost_scsi;
	struct vhost_virtqueue *vq;
	u32 reason;

	if (!vs)
		return;

	mutex_lock(&vs->dev.mutex);

	if (plug)
		reason = VIRTIO_SCSI_EVT_RESET_RESCAN;
	else
		reason = VIRTIO_SCSI_EVT_RESET_REMOVED;

	vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
	mutex_lock(&vq->mutex);
	if (vhost_has_feature(vq, VIRTIO_SCSI_F_HOTPLUG))
		vhost_scsi_send_evt(vs, tpg, lun,
				   VIRTIO_SCSI_T_TRANSPORT_RESET, reason);
	mutex_unlock(&vq->mutex);
	mutex_unlock(&vs->dev.mutex);
}


static void synthfilt_build_sb_samples (QDM2Context *q, GetBitContext *gb, int length, int sb_min, int sb_max)

{

    int sb, j, k, n, ch, run, channels;

    int joined_stereo, zero_encoding, chs;

    int type34_first;

    float type34_div = 0;

    float type34_predictor;

    float samples[10], sign_bits[16];

    if (length == 0) {

        // If no data use noise

        for (sb=sb_min; sb < sb_max; sb++)

            build_sb_samples_from_noise (q, sb);

        return;

    }

    for (sb = sb_min; sb < sb_max; sb++) {

        FIX_NOISE_IDX(q->noise_idx);

        channels = q->nb_channels;

        if (q->nb_channels <= 1 || sb < 12)

            joined_stereo = 0;

        else if (sb >= 24)

            joined_stereo = 1;

        else

            joined_stereo = (BITS_LEFT(length,gb) >= 1) ? get_bits1 (gb) : 0;

        if (joined_stereo) {

            if (BITS_LEFT(length,gb) >= 16)

                for (j = 0; j < 16; j++)

                    sign_bits[j] = get_bits1 (gb);

            for (j = 0; j < 64; j++)

                if (q->coding_method[1][sb][j] > q->coding_method[0][sb][j])

                    q->coding_method[0][sb][j] = q->coding_method[1][sb][j];

            fix_coding_method_array(sb, q->nb_channels, q->coding_method);

            channels = 1;

        }

        for (ch = 0; ch < channels; ch++) {

            zero_encoding = (BITS_LEFT(length,gb) >= 1) ? get_bits1(gb) : 0;

            type34_predictor = 0.0;

            type34_first = 1;

            for (j = 0; j < 128; ) {

                switch (q->coding_method[ch][sb][j / 2]) {

                    case 8:

                        if (BITS_LEFT(length,gb) >= 10) {

                            if (zero_encoding) {

                                for (k = 0; k < 5; k++) {

                                    if ((j + 2 * k) >= 128)

                                        break;

                                    samples[2 * k] = get_bits1(gb) ? dequant_1bit[joined_stereo][2 * get_bits1(gb)] : 0;

                                }

                            } else {

                                n = get_bits(gb, 8);

                                for (k = 0; k < 5; k++)

                                    samples[2 * k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];

                            }

                            for (k = 0; k < 5; k++)

                                samples[2 * k + 1] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        } else {

                            for (k = 0; k < 10; k++)

                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 10;

                        break;

                    case 10:

                        if (BITS_LEFT(length,gb) >= 1) {

                            float f = 0.81;

                            if (get_bits1(gb))

                                f = -f;

                            f -= noise_samples[((sb + 1) * (j +5 * ch + 1)) & 127] * 9.0 / 40.0;

                            samples[0] = f;

                        } else {

                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 1;

                        break;

                    case 16:

                        if (BITS_LEFT(length,gb) >= 10) {

                            if (zero_encoding) {

                                for (k = 0; k < 5; k++) {

                                    if ((j + k) >= 128)

                                        break;

                                    samples[k] = (get_bits1(gb) == 0) ? 0 : dequant_1bit[joined_stereo][2 * get_bits1(gb)];

                                }

                            } else {

                                n = get_bits (gb, 8);

                                for (k = 0; k < 5; k++)

                                    samples[k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];

                            }

                        } else {

                            for (k = 0; k < 5; k++)

                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 5;

                        break;

                    case 24:

                        if (BITS_LEFT(length,gb) >= 7) {

                            n = get_bits(gb, 7);

                            for (k = 0; k < 3; k++)

                                samples[k] = (random_dequant_type24[n][k] - 2.0) * 0.5;

                        } else {

                            for (k = 0; k < 3; k++)

                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 3;

                        break;

                    case 30:

                        if (BITS_LEFT(length,gb) >= 4)

                            samples[0] = type30_dequant[qdm2_get_vlc(gb, &vlc_tab_type30, 0, 1)];

                        else

                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        run = 1;

                        break;

                    case 34:

                        if (BITS_LEFT(length,gb) >= 7) {

                            if (type34_first) {

                                type34_div = (float)(1 << get_bits(gb, 2));

                                samples[0] = ((float)get_bits(gb, 5) - 16.0) / 15.0;

                                type34_predictor = samples[0];

                                type34_first = 0;

                            } else {

                                samples[0] = type34_delta[qdm2_get_vlc(gb, &vlc_tab_type34, 0, 1)] / type34_div + type34_predictor;

                                type34_predictor = samples[0];

                            }

                        } else {

                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 1;

                        break;

                    default:

                        samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        run = 1;

                        break;

                }

                if (joined_stereo) {

                    float tmp[10][MPA_MAX_CHANNELS];

                    for (k = 0; k < run; k++) {

                        tmp[k][0] = samples[k];

                        tmp[k][1] = (sign_bits[(j + k) / 8]) ? -samples[k] : samples[k];

                    }

                    for (chs = 0; chs < q->nb_channels; chs++)

                        for (k = 0; k < run; k++)

                            if ((j + k) < 128)

                                q->sb_samples[chs][j + k][sb] = q->tone_level[chs][sb][((j + k)/2)] * tmp[k][chs];

                } else {

                    for (k = 0; k < run; k++)

                        if ((j + k) < 128)

                            q->sb_samples[ch][j + k][sb] = q->tone_level[ch][sb][(j + k)/2] * samples[k];

                }

                j += run;

            } // j loop

        } // channel loop

    } // subband loop

}


static bool get_desc(struct desc_struct *out, unsigned short sel)
{
	struct desc_ptr gdt_desc = {0, 0};
	unsigned long desc_base;

#ifdef CONFIG_MODIFY_LDT_SYSCALL
	if ((sel & SEGMENT_TI_MASK) == SEGMENT_LDT) {
		bool success = false;
		struct ldt_struct *ldt;

		/* Bits [15:3] contain the index of the desired entry. */
		sel >>= 3;

		mutex_lock(&current->active_mm->context.lock);
		ldt = current->active_mm->context.ldt;
		if (ldt && sel < ldt->nr_entries) {
			*out = ldt->entries[sel];
			success = true;
		}

		mutex_unlock(&current->active_mm->context.lock);

		return success;
	}
#endif
	native_store_gdt(&gdt_desc);

	/*
	 * Segment descriptors have a size of 8 bytes. Thus, the index is
	 * multiplied by 8 to obtain the memory offset of the desired descriptor
	 * from the base of the GDT. As bits [15:3] of the segment selector
	 * contain the index, it can be regarded as multiplied by 8 already.
	 * All that remains is to clear bits [2:0].
	 */
	desc_base = sel & ~(SEGMENT_RPL_MASK | SEGMENT_TI_MASK);

	if (desc_base > gdt_desc.size)
		return false;

	*out = *(struct desc_struct *)(gdt_desc.address + desc_base);
	return true;
}


static inline bool peers(struct mount *m1, struct mount *m2)
{
	return m1->mnt_group_id == m2->mnt_group_id && m1->mnt_group_id;
}


static av_cold int vc2_encode_init(AVCodecContext *avctx)

{

    Plane *p;

    SubBand *b;

    int i, j, level, o, shift, ret;

    const AVPixFmtDescriptor *fmt = av_pix_fmt_desc_get(avctx->pix_fmt);

    const int depth = fmt->comp[0].depth;

    VC2EncContext *s = avctx->priv_data;

    s->picture_number = 0;

    /* Total allowed quantization range */

    s->q_ceil    = DIRAC_MAX_QUANT_INDEX;

    s->ver.major = 2;

    s->ver.minor = 0;

    s->profile   = 3;

    s->level     = 3;

    s->base_vf   = -1;

    s->strict_compliance = 1;

    s->q_avg = 0;

    s->slice_max_bytes = 0;

    s->slice_min_bytes = 0;

    /* Mark unknown as progressive */

    s->interlaced = !((avctx->field_order == AV_FIELD_UNKNOWN) ||

                      (avctx->field_order == AV_FIELD_PROGRESSIVE));

    for (i = 0; i < base_video_fmts_len; i++) {

        const VC2BaseVideoFormat *fmt = &base_video_fmts[i];

        if (avctx->pix_fmt != fmt->pix_fmt)

            continue;

        if (avctx->time_base.num != fmt->time_base.num)

            continue;

        if (avctx->time_base.den != fmt->time_base.den)

            continue;

        if (avctx->width != fmt->width)

            continue;

        if (avctx->height != fmt->height)

            continue;

        if (s->interlaced != fmt->interlaced)

            continue;

        s->base_vf = i;

        s->level   = base_video_fmts[i].level;

        break;

    }

    if (s->interlaced)

        av_log(avctx, AV_LOG_WARNING, "Interlacing enabled!\n");

    if ((s->slice_width  & (s->slice_width  - 1)) ||

        (s->slice_height & (s->slice_height - 1))) {

        av_log(avctx, AV_LOG_ERROR, "Slice size is not a power of two!\n");

        return AVERROR_UNKNOWN;

    }

    if ((s->slice_width > avctx->width) ||

        (s->slice_height > avctx->height)) {

        av_log(avctx, AV_LOG_ERROR, "Slice size is bigger than the image!\n");

        return AVERROR_UNKNOWN;

    }

    if (s->base_vf <= 0) {

        if (avctx->strict_std_compliance < FF_COMPLIANCE_STRICT) {

            s->strict_compliance = s->base_vf = 0;

            av_log(avctx, AV_LOG_WARNING, "Format does not strictly comply with VC2 specs\n");

        } else {

            av_log(avctx, AV_LOG_WARNING, "Given format does not strictly comply with "

                   "the specifications, decrease strictness to use it.\n");

            return AVERROR_UNKNOWN;

        }

    } else {

        av_log(avctx, AV_LOG_INFO, "Selected base video format = %i (%s)\n",

               s->base_vf, base_video_fmts[s->base_vf].name);

    }

    /* Chroma subsampling */

    ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);

    if (ret)

        return ret;

    /* Bit depth and color range index */

    if (depth == 8 && avctx->color_range == AVCOL_RANGE_JPEG) {

        s->bpp = 1;

        s->bpp_idx = 1;

        s->diff_offset = 128;

    } else if (depth == 8 && (avctx->color_range == AVCOL_RANGE_MPEG ||

               avctx->color_range == AVCOL_RANGE_UNSPECIFIED)) {

        s->bpp = 1;

        s->bpp_idx = 2;

        s->diff_offset = 128;

    } else if (depth == 10) {

        s->bpp = 2;

        s->bpp_idx = 3;

        s->diff_offset = 512;

    } else {

        s->bpp = 2;

        s->bpp_idx = 4;

        s->diff_offset = 2048;

    }

    /* Planes initialization */

    for (i = 0; i < 3; i++) {

        int w, h;

        p = &s->plane[i];

        p->width      = avctx->width  >> (i ? s->chroma_x_shift : 0);

        p->height     = avctx->height >> (i ? s->chroma_y_shift : 0);

        if (s->interlaced)

            p->height >>= 1;

        p->dwt_width  = w = FFALIGN(p->width,  (1 << s->wavelet_depth));

        p->dwt_height = h = FFALIGN(p->height, (1 << s->wavelet_depth));

        p->coef_stride = FFALIGN(p->dwt_width, 32);

        p->coef_buf = av_malloc(p->coef_stride*p->dwt_height*sizeof(dwtcoef));

        if (!p->coef_buf)

            goto alloc_fail;

        for (level = s->wavelet_depth-1; level >= 0; level--) {

            w = w >> 1;

            h = h >> 1;

            for (o = 0; o < 4; o++) {

                b = &p->band[level][o];

                b->width  = w;

                b->height = h;

                b->stride = p->coef_stride;

                shift = (o > 1)*b->height*b->stride + (o & 1)*b->width;

                b->buf = p->coef_buf + shift;

            }

        }

        /* DWT init */

        if (ff_vc2enc_init_transforms(&s->transform_args[i].t,

                                      s->plane[i].coef_stride,

                                      s->plane[i].dwt_height))

            goto alloc_fail;

    }

    /* Slices */

    s->num_x = s->plane[0].dwt_width/s->slice_width;

    s->num_y = s->plane[0].dwt_height/s->slice_height;

    s->slice_args = av_calloc(s->num_x*s->num_y, sizeof(SliceArgs));

    if (!s->slice_args)

        goto alloc_fail;

    /* Lookup tables */

    s->coef_lut_len = av_malloc(COEF_LUT_TAB*(s->q_ceil+1)*sizeof(*s->coef_lut_len));

    if (!s->coef_lut_len)

        goto alloc_fail;

    s->coef_lut_val = av_malloc(COEF_LUT_TAB*(s->q_ceil+1)*sizeof(*s->coef_lut_val));

    if (!s->coef_lut_val)

        goto alloc_fail;

    for (i = 0; i < s->q_ceil; i++) {

        uint8_t  *len_lut = &s->coef_lut_len[i*COEF_LUT_TAB];

        uint32_t *val_lut = &s->coef_lut_val[i*COEF_LUT_TAB];

        for (j = 0; j < COEF_LUT_TAB; j++) {

            get_vc2_ue_uint(QUANT(j, ff_dirac_qscale_tab[i]),

                            &len_lut[j], &val_lut[j]);

            if (len_lut[j] != 1) {

                len_lut[j] += 1;

                val_lut[j] <<= 1;

            } else {

                val_lut[j] = 1;

            }

        }

    }

    return 0;

alloc_fail:

    vc2_encode_end(avctx);

    av_log(avctx, AV_LOG_ERROR, "Unable to allocate memory!\n");

    return AVERROR(ENOMEM);

}


bool IsFormTextArea(PDFiumPage::Area area, int form_type) {
  if (form_type == FPDF_FORMFIELD_UNKNOWN)
    return false;

  DCHECK_EQ(area, PDFiumPage::FormTypeToArea(form_type));
  return area == PDFiumPage::FORM_TEXT_AREA;
}


void GLES2DecoderImpl::DoVertexAttrib1fv(GLuint index, const GLfloat* v) {
  GLfloat t[4] = { v[0], 0.0f, 0.0f, 1.0f, };
  if (SetVertexAttribValue("glVertexAttrib1fv", index, t)) {
    glVertexAttrib1fv(index, v);
  }
}


static VOID ParaNdis_DeviceFiltersUpdateRxMode(PARANDIS_ADAPTER *pContext)
{
    u8 val;
    ULONG f = pContext->PacketFilter;
    val = (f & NDIS_PACKET_TYPE_ALL_MULTICAST) ? 1 : 0;
    pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLMULTI, &val, sizeof(val), NULL, 0, 2);
    //SendControlMessage(pContext, VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_ALLUNI, &val, sizeof(val), NULL, 0, 2);
    val = (f & (NDIS_PACKET_TYPE_MULTICAST | NDIS_PACKET_TYPE_ALL_MULTICAST)) ? 0 : 1;
    pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOMULTI, &val, sizeof(val), NULL, 0, 2);
    val = (f & NDIS_PACKET_TYPE_DIRECTED) ? 0 : 1;
    pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOUNI, &val, sizeof(val), NULL, 0, 2);
    val = (f & NDIS_PACKET_TYPE_BROADCAST) ? 0 : 1;
    pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_NOBCAST, &val, sizeof(val), NULL, 0, 2);
    val = (f & NDIS_PACKET_TYPE_PROMISCUOUS) ? 1 : 0;
    pContext->CXPath.SendControlMessage(VIRTIO_NET_CTRL_RX_MODE, VIRTIO_NET_CTRL_RX_MODE_PROMISC, &val, sizeof(val), NULL, 0, 2);
}


mono_image_get_method_on_inst_token (MonoDynamicImage *assembly, MonoReflectionMethodOnTypeBuilderInst *m, gboolean create_methodspec)
{
	guint32 sig, token = 0;
	MonoType *type;
	MonoClass *klass;

	if (m->method_args) {
		MonoMethod *inflated;

		inflated = mono_reflection_method_on_tb_inst_get_handle (m);
		if (create_methodspec)
			token = mono_image_get_methodspec_token (assembly, inflated);
		else
			token = mono_image_get_inflated_method_token (assembly, inflated);
		return token;
	}

	token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, m));
	if (token)
		return token;

	if (is_sre_method_builder (mono_object_class (m->mb))) {
		MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)m->mb;
		MonoGenericClass *gclass;
		ReflectionMethodBuilder rmb;
		char *name;

		type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst);
		klass = mono_class_from_mono_type (type);
		gclass = type->data.generic_class;
		g_assert (gclass->is_dynamic);

		reflection_methodbuilder_from_method_builder (&rmb, mb);

		name = mono_string_to_utf8 (rmb.name);

		sig = method_builder_encode_signature (assembly, &rmb);

		token = mono_image_get_memberref_token (assembly, &klass->byval_arg, name, sig);
		g_free (name);
	} else if (is_sr_mono_method (mono_object_class (m->mb))) {
		MonoMethod *mm = ((MonoReflectionMethod *)m->mb)->method;

		type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst);
		klass = mono_class_from_mono_type (type);

		sig = method_encode_signature (assembly, mono_method_signature (mm));
		token = mono_image_get_memberref_token (assembly, &klass->byval_arg, mm->name, sig);
	} else {
		char *name = mono_type_get_full_name (mono_object_class (m->mb));
		g_error ("mono_image_get_method_on_inst_token: don't know how to handle %s", name);
	}

	mono_g_hash_table_insert (assembly->handleref_managed, m, GUINT_TO_POINTER (token));
	return token;
}


bool Parser::ParseOptionalExpr(ParseNodePtr* pnode, bool fUnaryOrParen, int oplMin, BOOL *pfCanAssign, BOOL fAllowIn, BOOL fAllowEllipsis, _Inout_opt_ IdentToken* pToken)
{
    *pnode = nullptr;
    if (m_token.tk == tkRCurly ||
        m_token.tk == tkRBrack ||
        m_token.tk == tkRParen ||
        m_token.tk == tkSColon ||
        m_token.tk == tkColon ||
        m_token.tk == tkComma ||
        m_token.tk == tkLimKwd ||
        m_pscan->FHadNewLine())
    {
        return false;
    }

    IdentToken token;
    ParseNodePtr pnodeT = ParseExpr<buildAST>(oplMin, pfCanAssign, fAllowIn, fAllowEllipsis, nullptr /*pNameHint*/, nullptr /*pHintLength*/, nullptr /*pShortNameOffset*/, &token, fUnaryOrParen);
    // Detect nested function escapes of the pattern "return function(){...}" or "yield function(){...}".
    // Doing so in the parser allows us to disable stack-nested-functions in common cases where an escape
    // is not detected at byte code gen time because of deferred parsing.
    this->MarkEscapingRef(pnodeT, &token);
    if (pToken)
    {
        *pToken = token;
    }
    *pnode = pnodeT;
    return true;
}


static bool LookingAtNAL(const std::string& encoded, size_t pos) {
  return pos + 3 < encoded.size() &&
      encoded[pos] == 0 && encoded[pos + 1] == 0 &&
      encoded[pos + 2] == 0 && encoded[pos + 3] == 1;
}


static inline void lock_mount_hash(void)
{
	write_seqlock(&mount_lock);
}


static int get_codec_data(AVIOContext *pb, AVStream *vst,

                          AVStream *ast, int myth)

{

    nuv_frametype frametype;

    if (!vst && !myth)

        return 1; // no codec data needed

    while (!pb->eof_reached) {

        int size, subtype;

        frametype = avio_r8(pb);

        switch (frametype) {

        case NUV_EXTRADATA:

            subtype = avio_r8(pb);

            avio_skip(pb, 6);

            size = PKTSIZE(avio_rl32(pb));

            if (vst && subtype == 'R') {

                vst->codec->extradata_size = size;

                vst->codec->extradata      = av_malloc(size);

                avio_read(pb, vst->codec->extradata, size);

                size = 0;

                if (!myth)

                    return 1;

            }

            break;

        case NUV_MYTHEXT:

            avio_skip(pb, 7);

            size = PKTSIZE(avio_rl32(pb));

            if (size != 128 * 4)

                break;

            avio_rl32(pb); // version

            if (vst) {

                vst->codec->codec_tag = avio_rl32(pb);

                vst->codec->codec_id =

                    ff_codec_get_id(ff_codec_bmp_tags, vst->codec->codec_tag);

                if (vst->codec->codec_tag == MKTAG('R', 'J', 'P', 'G'))

                    vst->codec->codec_id = AV_CODEC_ID_NUV;

            } else

                avio_skip(pb, 4);

            if (ast) {

                int id;

                ast->codec->codec_tag             = avio_rl32(pb);

                ast->codec->sample_rate           = avio_rl32(pb);

                ast->codec->bits_per_coded_sample = avio_rl32(pb);

                ast->codec->channels              = avio_rl32(pb);

                ast->codec->channel_layout        = 0;

                id = ff_wav_codec_get_id(ast->codec->codec_tag,

                                         ast->codec->bits_per_coded_sample);

                if (id == AV_CODEC_ID_NONE) {

                    id = ff_codec_get_id(nuv_audio_tags, ast->codec->codec_tag);

                    if (id == AV_CODEC_ID_PCM_S16LE)

                        id = ff_get_pcm_codec_id(ast->codec->bits_per_coded_sample,

                                                 0, 0, ~1);

                }

                ast->codec->codec_id = id;

                ast->need_parsing = AVSTREAM_PARSE_FULL;

            } else

                avio_skip(pb, 4 * 4);

            size -= 6 * 4;

            avio_skip(pb, size);

            return 1;

        case NUV_SEEKP:

            size = 11;

            break;

        default:

            avio_skip(pb, 7);

            size = PKTSIZE(avio_rl32(pb));

            break;

        }

        avio_skip(pb, size);

    }

    return 0;

}


static int count_commas(char *s)
{
	int n = 0;
	while (*s)
	{
		if (*s == ',')
			n ++;
		s ++;
	}
	return n;
}


const char* CodeFromNative(const base::NativeEvent& native_event) {
  const uint16 scan_code = GetScanCodeFromLParam(native_event.lParam);
  return CodeForWindowsScanCode(scan_code);
}


static void *ff_avio_child_next(void *obj, void *prev)

{

    AVIOContext *s = obj;

    AVIOInternal *internal = s->opaque;

    return prev ? NULL : internal->h;

}


 void PrintPreviewUI::OnReloadPrintersList() {
   web_ui()->CallJavascriptFunction("reloadPrintersList");
 }


error::Error GLES2DecoderImpl::HandleClientWaitSync(
    uint32_t immediate_data_size, const void* cmd_data) {
  if (!unsafe_es3_apis_enabled())
    return error::kUnknownCommand;
  const gles2::cmds::ClientWaitSync& c =
      *static_cast<const gles2::cmds::ClientWaitSync*>(cmd_data);
  GLuint sync = static_cast<GLuint>(c.sync);
  GLbitfield flags = static_cast<GLbitfield>(c.flags);
  GLuint64 timeout = GLES2Util::MapTwoUint32ToUint64(c.timeout_0, c.timeout_1);
  typedef cmds::ClientWaitSync::Result Result;
  Result* result_dst = GetSharedMemoryAs<Result*>(
      c.result_shm_id, c.result_shm_offset, sizeof(*result_dst));
  if (!result_dst) {
    return error::kOutOfBounds;
  }
  if (*result_dst != GL_WAIT_FAILED) {
    return error::kInvalidArguments;
  }
  GLsync service_sync = 0;
  if (!group_->GetSyncServiceId(sync, &service_sync)) {
    LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, "ClientWaitSync", "invalid sync");
    return error::kNoError;
  }
  *result_dst = glClientWaitSync(service_sync, flags, timeout);
  return error::kNoError;
}


static void finalize_request ( ngx_http_request_t * r , ngx_int_t rc ) {
 ngx_log_debug0 ( NGX_LOG_DEBUG_HTTP , r -> connection -> log , 0 , "finalize Passenger request" ) ;
 }


static int compat_do_replace(struct net *net, void __user *user,
			     unsigned int len)
{
	int ret;
	struct compat_arpt_replace tmp;
	struct xt_table_info *newinfo;
	void *loc_cpu_entry;
	struct arpt_entry *iter;

	if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
		return -EFAULT;

	/* overflow check */
	if (tmp.size >= INT_MAX / num_possible_cpus())
		return -ENOMEM;
	if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
		return -ENOMEM;
	if (tmp.num_counters == 0)
		return -EINVAL;

	tmp.name[sizeof(tmp.name)-1] = 0;

	newinfo = xt_alloc_table_info(tmp.size);
	if (!newinfo)
		return -ENOMEM;

	loc_cpu_entry = newinfo->entries;
	if (copy_from_user(loc_cpu_entry, user + sizeof(tmp), tmp.size) != 0) {
		ret = -EFAULT;
		goto free_newinfo;
	}

	ret = translate_compat_table(tmp.name, tmp.valid_hooks,
				     &newinfo, &loc_cpu_entry, tmp.size,
				     tmp.num_entries, tmp.hook_entry,
				     tmp.underflow);
	if (ret != 0)
		goto free_newinfo;

	duprintf("compat_do_replace: Translated table\n");

	ret = __do_replace(net, tmp.name, tmp.valid_hooks, newinfo,
			   tmp.num_counters, compat_ptr(tmp.counters));
	if (ret)
		goto free_newinfo_untrans;
	return 0;

 free_newinfo_untrans:
	xt_entry_foreach(iter, loc_cpu_entry, newinfo->size)
		cleanup_entry(iter);
 free_newinfo:
	xt_free_table_info(newinfo);
	return ret;
}