Home | History | Annotate | Download | only in libhwcomposer
      1 /*
      2  * Copyright (C) 2010 The Android Open Source Project
      3  * Copyright (C) 2012-2014, The Linux Foundation All rights reserved.
      4  *
      5  * Not a Contribution, Apache license notifications and license are retained
      6  * for attribution purposes only.
      7  *
      8  * Licensed under the Apache License, Version 2.0 (the "License");
      9  * you may not use this file except in compliance with the License.
     10  * You may obtain a copy of the License at
     11  *
     12  *      http://www.apache.org/licenses/LICENSE-2.0
     13  *
     14  * Unless required by applicable law or agreed to in writing, software
     15  * distributed under the License is distributed on an "AS IS" BASIS,
     16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     17  * See the License for the specific language governing permissions and
     18  * limitations under the License.
     19  */
     20 #define ATRACE_TAG (ATRACE_TAG_GRAPHICS | ATRACE_TAG_HAL)
     21 #define HWC_UTILS_DEBUG 0
     22 #include <math.h>
     23 #include <sys/ioctl.h>
     24 #include <linux/fb.h>
     25 #include <binder/IServiceManager.h>
     26 #include <EGL/egl.h>
     27 #include <cutils/properties.h>
     28 #include <utils/Trace.h>
     29 #include <gralloc_priv.h>
     30 #include <overlay.h>
     31 #include <overlayRotator.h>
     32 #include <overlayWriteback.h>
     33 #include "hwc_utils.h"
     34 #include "hwc_mdpcomp.h"
     35 #include "hwc_fbupdate.h"
     36 #include "hwc_ad.h"
     37 #include "mdp_version.h"
     38 #include "hwc_copybit.h"
     39 #include "hwc_dump_layers.h"
     40 #include "external.h"
     41 #include "virtual.h"
     42 #include "hwc_qclient.h"
     43 #include "QService.h"
     44 #include "comptype.h"
     45 #include "hwc_virtual.h"
     46 #include "qd_utils.h"
     47 
     48 using namespace qClient;
     49 using namespace qService;
     50 using namespace android;
     51 using namespace overlay;
     52 using namespace overlay::utils;
     53 namespace ovutils = overlay::utils;
     54 
     55 #ifdef QCOM_BSP
     56 #ifdef __cplusplus
     57 extern "C" {
     58 #endif
     59 
     60 EGLAPI EGLBoolean eglGpuPerfHintQCOM(EGLDisplay dpy, EGLContext ctx,
     61                                            EGLint *attrib_list);
     62 #define EGL_GPU_HINT_1        0x32D0
     63 #define EGL_GPU_HINT_2        0x32D1
     64 
     65 #define EGL_GPU_LEVEL_0       0x0
     66 #define EGL_GPU_LEVEL_1       0x1
     67 #define EGL_GPU_LEVEL_2       0x2
     68 #define EGL_GPU_LEVEL_3       0x3
     69 #define EGL_GPU_LEVEL_4       0x4
     70 #define EGL_GPU_LEVEL_5       0x5
     71 
     72 #ifdef __cplusplus
     73 }
     74 #endif
     75 #endif
     76 
     77 namespace qhwc {
     78 
     79 bool isValidResolution(hwc_context_t *ctx, uint32_t xres, uint32_t yres)
     80 {
     81     return !((xres > qdutils::MAX_DISPLAY_DIM &&
     82                 !isDisplaySplit(ctx, HWC_DISPLAY_PRIMARY)) ||
     83             (xres < MIN_DISPLAY_XRES || yres < MIN_DISPLAY_YRES));
     84 }
     85 
     86 void changeResolution(hwc_context_t *ctx, int xres_orig, int yres_orig,
     87                       int width, int height) {
     88     //Store original display resolution.
     89     ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres_new = xres_orig;
     90     ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres_new = yres_orig;
     91     ctx->dpyAttr[HWC_DISPLAY_PRIMARY].customFBSize = false;
     92     char property[PROPERTY_VALUE_MAX] = {'\0'};
     93     char *yptr = NULL;
     94     if (property_get("debug.hwc.fbsize", property, NULL) > 0) {
     95         yptr = strcasestr(property,"x");
     96         int xres_new = atoi(property);
     97         int yres_new = atoi(yptr + 1);
     98         if (isValidResolution(ctx,xres_new,yres_new) &&
     99                  xres_new != xres_orig && yres_new != yres_orig) {
    100             ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres_new = xres_new;
    101             ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres_new = yres_new;
    102             ctx->dpyAttr[HWC_DISPLAY_PRIMARY].customFBSize = true;
    103 
    104             //Caluculate DPI according to changed resolution.
    105             float xdpi = ((float)xres_new * 25.4f) / (float)width;
    106             float ydpi = ((float)yres_new * 25.4f) / (float)height;
    107             ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xdpi = xdpi;
    108             ctx->dpyAttr[HWC_DISPLAY_PRIMARY].ydpi = ydpi;
    109         }
    110     }
    111 }
    112 
    113 static int openFramebufferDevice(hwc_context_t *ctx)
    114 {
    115     struct fb_fix_screeninfo finfo;
    116     struct fb_var_screeninfo info;
    117 
    118     int fb_fd = openFb(HWC_DISPLAY_PRIMARY);
    119     if(fb_fd < 0) {
    120         ALOGE("%s: Error Opening FB : %s", __FUNCTION__, strerror(errno));
    121         return -errno;
    122     }
    123 
    124     if (ioctl(fb_fd, FBIOGET_VSCREENINFO, &info) == -1) {
    125         ALOGE("%s:Error in ioctl FBIOGET_VSCREENINFO: %s", __FUNCTION__,
    126                                                        strerror(errno));
    127         close(fb_fd);
    128         return -errno;
    129     }
    130 
    131     if (int(info.width) <= 0 || int(info.height) <= 0) {
    132         // the driver doesn't return that information
    133         // default to 160 dpi
    134         info.width  = (int)(((float)info.xres * 25.4f)/160.0f + 0.5f);
    135         info.height = (int)(((float)info.yres * 25.4f)/160.0f + 0.5f);
    136     }
    137 
    138     float xdpi = ((float)info.xres * 25.4f) / (float)info.width;
    139     float ydpi = ((float)info.yres * 25.4f) / (float)info.height;
    140 
    141 #ifdef MSMFB_METADATA_GET
    142     struct msmfb_metadata metadata;
    143     memset(&metadata, 0 , sizeof(metadata));
    144     metadata.op = metadata_op_frame_rate;
    145 
    146     if (ioctl(fb_fd, MSMFB_METADATA_GET, &metadata) == -1) {
    147         ALOGE("%s:Error retrieving panel frame rate: %s", __FUNCTION__,
    148                                                       strerror(errno));
    149         close(fb_fd);
    150         return -errno;
    151     }
    152 
    153     float fps  = (float)metadata.data.panel_frame_rate;
    154 #else
    155     //XXX: Remove reserved field usage on all baselines
    156     //The reserved[3] field is used to store FPS by the driver.
    157     float fps  = info.reserved[3] & 0xFF;
    158 #endif
    159 
    160     if (ioctl(fb_fd, FBIOGET_FSCREENINFO, &finfo) == -1) {
    161         ALOGE("%s:Error in ioctl FBIOGET_FSCREENINFO: %s", __FUNCTION__,
    162                                                        strerror(errno));
    163         close(fb_fd);
    164         return -errno;
    165     }
    166 
    167     ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd = fb_fd;
    168     //xres, yres may not be 32 aligned
    169     ctx->dpyAttr[HWC_DISPLAY_PRIMARY].stride = finfo.line_length /(info.xres/8);
    170     ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres = info.xres;
    171     ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres = info.yres;
    172     ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xdpi = xdpi;
    173     ctx->dpyAttr[HWC_DISPLAY_PRIMARY].ydpi = ydpi;
    174     ctx->dpyAttr[HWC_DISPLAY_PRIMARY].vsync_period =
    175             (uint32_t)(1000000000l / fps);
    176 
    177     //To change resolution of primary display
    178     changeResolution(ctx, info.xres, info.yres, info.width, info.height);
    179 
    180     //Unblank primary on first boot
    181     if(ioctl(fb_fd, FBIOBLANK,FB_BLANK_UNBLANK) < 0) {
    182         ALOGE("%s: Failed to unblank display", __FUNCTION__);
    183         return -errno;
    184     }
    185     ctx->dpyAttr[HWC_DISPLAY_PRIMARY].isActive = true;
    186 
    187     return 0;
    188 }
    189 
    190 void initContext(hwc_context_t *ctx)
    191 {
    192     openFramebufferDevice(ctx);
    193     char value[PROPERTY_VALUE_MAX];
    194     ctx->mMDP.version = qdutils::MDPVersion::getInstance().getMDPVersion();
    195     ctx->mMDP.hasOverlay = qdutils::MDPVersion::getInstance().hasOverlay();
    196     ctx->mMDP.panel = qdutils::MDPVersion::getInstance().getPanelType();
    197     overlay::Overlay::initOverlay();
    198     ctx->mOverlay = overlay::Overlay::getInstance();
    199     ctx->mRotMgr = RotMgr::getInstance();
    200 
    201     //Is created and destroyed only once for primary
    202     //For external it could get created and destroyed multiple times depending
    203     //on what external we connect to.
    204     ctx->mFBUpdate[HWC_DISPLAY_PRIMARY] =
    205         IFBUpdate::getObject(ctx, HWC_DISPLAY_PRIMARY);
    206 
    207     // Check if the target supports copybit compostion (dyn/mdp) to
    208     // decide if we need to open the copybit module.
    209     int compositionType =
    210         qdutils::QCCompositionType::getInstance().getCompositionType();
    211 
    212     // Only MDP copybit is used
    213     if ((compositionType & (qdutils::COMPOSITION_TYPE_DYN |
    214             qdutils::COMPOSITION_TYPE_MDP)) &&
    215             (qdutils::MDPVersion::getInstance().getMDPVersion() ==
    216             qdutils::MDP_V3_0_4)) {
    217         ctx->mCopyBit[HWC_DISPLAY_PRIMARY] = new CopyBit(ctx,
    218                                                          HWC_DISPLAY_PRIMARY);
    219     }
    220 
    221     ctx->mExtDisplay = new ExternalDisplay(ctx);
    222     ctx->mVirtualDisplay = new VirtualDisplay(ctx);
    223     ctx->mVirtualonExtActive = false;
    224     ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].isActive = false;
    225     ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].connected = false;
    226     ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].isActive = false;
    227     ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].connected = false;
    228     ctx->dpyAttr[HWC_DISPLAY_PRIMARY].mDownScaleMode= false;
    229     ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].mDownScaleMode = false;
    230     ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].mDownScaleMode = false;
    231 
    232     ctx->mMDPComp[HWC_DISPLAY_PRIMARY] =
    233          MDPComp::getObject(ctx, HWC_DISPLAY_PRIMARY);
    234     ctx->dpyAttr[HWC_DISPLAY_PRIMARY].connected = true;
    235     //Initialize the primary display viewFrame info
    236     ctx->mViewFrame[HWC_DISPLAY_PRIMARY].left = 0;
    237     ctx->mViewFrame[HWC_DISPLAY_PRIMARY].top = 0;
    238     ctx->mViewFrame[HWC_DISPLAY_PRIMARY].right =
    239         (int)ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres;
    240     ctx->mViewFrame[HWC_DISPLAY_PRIMARY].bottom =
    241          (int)ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres;
    242 
    243     ctx->mVDSEnabled = false;
    244     if((property_get("persist.hwc.enable_vds", value, NULL) > 0)) {
    245         if(atoi(value) != 0) {
    246             ctx->mVDSEnabled = true;
    247         }
    248     }
    249     ctx->mHWCVirtual = HWCVirtualBase::getObject(ctx->mVDSEnabled);
    250 
    251     for (uint32_t i = 0; i < HWC_NUM_DISPLAY_TYPES; i++) {
    252         ctx->mHwcDebug[i] = new HwcDebug(i);
    253         ctx->mLayerRotMap[i] = new LayerRotMap();
    254         ctx->mAnimationState[i] = ANIMATION_STOPPED;
    255         ctx->dpyAttr[i].mActionSafePresent = false;
    256         ctx->dpyAttr[i].mAsWidthRatio = 0;
    257         ctx->dpyAttr[i].mAsHeightRatio = 0;
    258     }
    259 
    260     for (uint32_t i = 0; i < HWC_NUM_DISPLAY_TYPES; i++) {
    261         ctx->mPrevHwLayerCount[i] = 0;
    262     }
    263 
    264     MDPComp::init(ctx);
    265     ctx->mAD = new AssertiveDisplay(ctx);
    266 
    267     ctx->vstate.enable = false;
    268     ctx->vstate.fakevsync = false;
    269     ctx->mExtOrientation = 0;
    270     ctx->numActiveDisplays = 1;
    271 
    272     //Right now hwc starts the service but anybody could do it, or it could be
    273     //independent process as well.
    274     QService::init();
    275     sp<IQClient> client = new QClient(ctx);
    276     interface_cast<IQService>(
    277             defaultServiceManager()->getService(
    278             String16("display.qservice")))->connect(client);
    279 
    280     // Initialize device orientation to its default orientation
    281     ctx->deviceOrientation = 0;
    282     ctx->mBufferMirrorMode = false;
    283 
    284     // Read the system property to determine if downscale feature is enabled.
    285     ctx->mMDPDownscaleEnabled = false;
    286     if(property_get("sys.hwc.mdp_downscale_enabled", value, "false")
    287             && !strcmp(value, "true")) {
    288         ctx->mMDPDownscaleEnabled = true;
    289     }
    290 
    291     ctx->enableABC = false;
    292     property_get("debug.sf.hwc.canUseABC", value, "0");
    293     ctx->enableABC  = atoi(value) ? true : false;
    294 
    295     // Initialize gpu perfomance hint related parameters
    296     property_get("sys.hwc.gpu_perf_mode", value, "0");
    297 #ifdef QCOM_BSP
    298     ctx->mGPUHintInfo.mGpuPerfModeEnable = atoi(value)? true : false;
    299 
    300     ctx->mGPUHintInfo.mEGLDisplay = NULL;
    301     ctx->mGPUHintInfo.mEGLContext = NULL;
    302     ctx->mGPUHintInfo.mCompositionState = COMPOSITION_STATE_MDP;
    303     ctx->mGPUHintInfo.mCurrGPUPerfMode = EGL_GPU_LEVEL_0;
    304 #endif
    305     memset(&(ctx->mPtorInfo), 0, sizeof(ctx->mPtorInfo));
    306     ALOGI("Initializing Qualcomm Hardware Composer");
    307     ALOGI("MDP version: %d", ctx->mMDP.version);
    308 }
    309 
    310 void closeContext(hwc_context_t *ctx)
    311 {
    312     if(ctx->mOverlay) {
    313         delete ctx->mOverlay;
    314         ctx->mOverlay = NULL;
    315     }
    316 
    317     if(ctx->mRotMgr) {
    318         delete ctx->mRotMgr;
    319         ctx->mRotMgr = NULL;
    320     }
    321 
    322     for(int i = 0; i < HWC_NUM_DISPLAY_TYPES; i++) {
    323         if(ctx->mCopyBit[i]) {
    324             delete ctx->mCopyBit[i];
    325             ctx->mCopyBit[i] = NULL;
    326         }
    327     }
    328 
    329     if(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd) {
    330         close(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd);
    331         ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd = -1;
    332     }
    333 
    334     if(ctx->mExtDisplay) {
    335         delete ctx->mExtDisplay;
    336         ctx->mExtDisplay = NULL;
    337     }
    338 
    339     for(int i = 0; i < HWC_NUM_DISPLAY_TYPES; i++) {
    340         if(ctx->mFBUpdate[i]) {
    341             delete ctx->mFBUpdate[i];
    342             ctx->mFBUpdate[i] = NULL;
    343         }
    344         if(ctx->mMDPComp[i]) {
    345             delete ctx->mMDPComp[i];
    346             ctx->mMDPComp[i] = NULL;
    347         }
    348         if(ctx->mHwcDebug[i]) {
    349             delete ctx->mHwcDebug[i];
    350             ctx->mHwcDebug[i] = NULL;
    351         }
    352         if(ctx->mLayerRotMap[i]) {
    353             delete ctx->mLayerRotMap[i];
    354             ctx->mLayerRotMap[i] = NULL;
    355         }
    356     }
    357     if(ctx->mHWCVirtual) {
    358         delete ctx->mHWCVirtual;
    359         ctx->mHWCVirtual = NULL;
    360     }
    361     if(ctx->mAD) {
    362         delete ctx->mAD;
    363         ctx->mAD = NULL;
    364     }
    365 
    366 
    367 }
    368 
    369 
    370 void dumpsys_log(android::String8& buf, const char* fmt, ...)
    371 {
    372     va_list varargs;
    373     va_start(varargs, fmt);
    374     buf.appendFormatV(fmt, varargs);
    375     va_end(varargs);
    376 }
    377 
    378 int getExtOrientation(hwc_context_t* ctx) {
    379     int extOrient = ctx->mExtOrientation;
    380     if(ctx->mBufferMirrorMode)
    381         extOrient = getMirrorModeOrientation(ctx);
    382     return extOrient;
    383 }
    384 
    385 /* Calculates the destination position based on the action safe rectangle */
    386 void getActionSafePosition(hwc_context_t *ctx, int dpy, hwc_rect_t& rect) {
    387     // Position
    388     int x = rect.left, y = rect.top;
    389     int w = rect.right - rect.left;
    390     int h = rect.bottom - rect.top;
    391 
    392     if(!ctx->dpyAttr[dpy].mActionSafePresent)
    393         return;
    394    // Read action safe properties
    395     int asWidthRatio = ctx->dpyAttr[dpy].mAsWidthRatio;
    396     int asHeightRatio = ctx->dpyAttr[dpy].mAsHeightRatio;
    397 
    398     float wRatio = 1.0;
    399     float hRatio = 1.0;
    400     float xRatio = 1.0;
    401     float yRatio = 1.0;
    402 
    403     int fbWidth = ctx->dpyAttr[dpy].xres;
    404     int fbHeight = ctx->dpyAttr[dpy].yres;
    405     if(ctx->dpyAttr[dpy].mDownScaleMode) {
    406         // if downscale Mode is enabled for external, need to query
    407         // the actual width and height, as that is the physical w & h
    408          ctx->mExtDisplay->getAttributes(fbWidth, fbHeight);
    409     }
    410 
    411 
    412     // Since external is rotated 90, need to swap width/height
    413     int extOrient = getExtOrientation(ctx);
    414 
    415     if(extOrient & HWC_TRANSFORM_ROT_90)
    416         swap(fbWidth, fbHeight);
    417 
    418     float asX = 0;
    419     float asY = 0;
    420     float asW = (float)fbWidth;
    421     float asH = (float)fbHeight;
    422 
    423     // based on the action safe ratio, get the Action safe rectangle
    424     asW = ((float)fbWidth * (1.0f -  (float)asWidthRatio / 100.0f));
    425     asH = ((float)fbHeight * (1.0f -  (float)asHeightRatio / 100.0f));
    426     asX = ((float)fbWidth - asW) / 2;
    427     asY = ((float)fbHeight - asH) / 2;
    428 
    429     // calculate the position ratio
    430     xRatio = (float)x/(float)fbWidth;
    431     yRatio = (float)y/(float)fbHeight;
    432     wRatio = (float)w/(float)fbWidth;
    433     hRatio = (float)h/(float)fbHeight;
    434 
    435     //Calculate the position...
    436     x = int((xRatio * asW) + asX);
    437     y = int((yRatio * asH) + asY);
    438     w = int(wRatio * asW);
    439     h = int(hRatio * asH);
    440 
    441     // Convert it back to hwc_rect_t
    442     rect.left = x;
    443     rect.top = y;
    444     rect.right = w + rect.left;
    445     rect.bottom = h + rect.top;
    446 
    447     return;
    448 }
    449 
    450 // This function gets the destination position for Seconday display
    451 // based on the position and aspect ratio with orientation
    452 void getAspectRatioPosition(hwc_context_t* ctx, int dpy, int extOrientation,
    453                             hwc_rect_t& inRect, hwc_rect_t& outRect) {
    454     // Physical display resolution
    455     float fbWidth  = (float)ctx->dpyAttr[dpy].xres;
    456     float fbHeight = (float)ctx->dpyAttr[dpy].yres;
    457     //display position(x,y,w,h) in correct aspectratio after rotation
    458     int xPos = 0;
    459     int yPos = 0;
    460     float width = fbWidth;
    461     float height = fbHeight;
    462     // Width/Height used for calculation, after rotation
    463     float actualWidth = fbWidth;
    464     float actualHeight = fbHeight;
    465 
    466     float wRatio = 1.0;
    467     float hRatio = 1.0;
    468     float xRatio = 1.0;
    469     float yRatio = 1.0;
    470     hwc_rect_t rect = {0, 0, (int)fbWidth, (int)fbHeight};
    471 
    472     Dim inPos(inRect.left, inRect.top, inRect.right - inRect.left,
    473                 inRect.bottom - inRect.top);
    474     Dim outPos(outRect.left, outRect.top, outRect.right - outRect.left,
    475                 outRect.bottom - outRect.top);
    476 
    477     Whf whf((uint32_t)fbWidth, (uint32_t)fbHeight, 0);
    478     eTransform extorient = static_cast<eTransform>(extOrientation);
    479     // To calculate the destination co-ordinates in the new orientation
    480     preRotateSource(extorient, whf, inPos);
    481 
    482     if(extOrientation & HAL_TRANSFORM_ROT_90) {
    483         // Swap width/height for input position
    484         swapWidthHeight(actualWidth, actualHeight);
    485         getAspectRatioPosition((int)fbWidth, (int)fbHeight, (int)actualWidth,
    486                                (int)actualHeight, rect);
    487         xPos = rect.left;
    488         yPos = rect.top;
    489         width = float(rect.right - rect.left);
    490         height = float(rect.bottom - rect.top);
    491     }
    492     xRatio = (float)((float)inPos.x/actualWidth);
    493     yRatio = (float)((float)inPos.y/actualHeight);
    494     wRatio = (float)((float)inPos.w/actualWidth);
    495     hRatio = (float)((float)inPos.h/actualHeight);
    496 
    497     //Calculate the pos9ition...
    498     outPos.x = uint32_t((xRatio * width) + (float)xPos);
    499     outPos.y = uint32_t((yRatio * height) + (float)yPos);
    500     outPos.w = uint32_t(wRatio * width);
    501     outPos.h = uint32_t(hRatio * height);
    502     ALOGD_IF(HWC_UTILS_DEBUG, "%s: Calculated AspectRatio Position: x = %d,"
    503                  "y = %d w = %d h = %d", __FUNCTION__, outPos.x, outPos.y,
    504                  outPos.w, outPos.h);
    505 
    506     // For sidesync, the dest fb will be in portrait orientation, and the crop
    507     // will be updated to avoid the black side bands, and it will be upscaled
    508     // to fit the dest RB, so recalculate
    509     // the position based on the new width and height
    510     if ((extOrientation & HWC_TRANSFORM_ROT_90) &&
    511                         isOrientationPortrait(ctx)) {
    512         hwc_rect_t r = {0, 0, 0, 0};
    513         //Calculate the position
    514         xRatio = (float)(outPos.x - xPos)/width;
    515         // GetaspectRatio -- tricky to get the correct aspect ratio
    516         // But we need to do this.
    517         getAspectRatioPosition((int)width, (int)height,
    518                                (int)width,(int)height, r);
    519         xPos = r.left;
    520         yPos = r.top;
    521         float tempHeight = float(r.bottom - r.top);
    522         yRatio = (float)yPos/height;
    523         wRatio = (float)outPos.w/width;
    524         hRatio = tempHeight/height;
    525 
    526         //Map the coordinates back to Framebuffer domain
    527         outPos.x = uint32_t(xRatio * fbWidth);
    528         outPos.y = uint32_t(yRatio * fbHeight);
    529         outPos.w = uint32_t(wRatio * fbWidth);
    530         outPos.h = uint32_t(hRatio * fbHeight);
    531 
    532         ALOGD_IF(HWC_UTILS_DEBUG, "%s: Calculated AspectRatio for device in"
    533                  "portrait: x = %d,y = %d w = %d h = %d", __FUNCTION__,
    534                  outPos.x, outPos.y,
    535                  outPos.w, outPos.h);
    536     }
    537     if(ctx->dpyAttr[dpy].mDownScaleMode) {
    538         int extW, extH;
    539         if(dpy == HWC_DISPLAY_EXTERNAL)
    540             ctx->mExtDisplay->getAttributes(extW, extH);
    541         else
    542             ctx->mVirtualDisplay->getAttributes(extW, extH);
    543         fbWidth  = (float)ctx->dpyAttr[dpy].xres;
    544         fbHeight = (float)ctx->dpyAttr[dpy].yres;
    545         //Calculate the position...
    546         xRatio = (float)outPos.x/fbWidth;
    547         yRatio = (float)outPos.y/fbHeight;
    548         wRatio = (float)outPos.w/fbWidth;
    549         hRatio = (float)outPos.h/fbHeight;
    550 
    551         outPos.x = uint32_t(xRatio * (float)extW);
    552         outPos.y = uint32_t(yRatio * (float)extH);
    553         outPos.w = uint32_t(wRatio * (float)extW);
    554         outPos.h = uint32_t(hRatio * (float)extH);
    555     }
    556     // Convert Dim to hwc_rect_t
    557     outRect.left = outPos.x;
    558     outRect.top = outPos.y;
    559     outRect.right = outPos.x + outPos.w;
    560     outRect.bottom = outPos.y + outPos.h;
    561 
    562     return;
    563 }
    564 
    565 bool isPrimaryPortrait(hwc_context_t *ctx) {
    566     int fbWidth = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres;
    567     int fbHeight = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres;
    568     if(fbWidth < fbHeight) {
    569         return true;
    570     }
    571     return false;
    572 }
    573 
    574 bool isOrientationPortrait(hwc_context_t *ctx) {
    575     if(isPrimaryPortrait(ctx)) {
    576         return !(ctx->deviceOrientation & 0x1);
    577     }
    578     return (ctx->deviceOrientation & 0x1);
    579 }
    580 
    581 void calcExtDisplayPosition(hwc_context_t *ctx,
    582                                private_handle_t *hnd,
    583                                int dpy,
    584                                hwc_rect_t& sourceCrop,
    585                                hwc_rect_t& displayFrame,
    586                                int& transform,
    587                                ovutils::eTransform& orient) {
    588     // Swap width and height when there is a 90deg transform
    589     int extOrient = getExtOrientation(ctx);
    590     if(dpy && ctx->mOverlay->isUIScalingOnExternalSupported()) {
    591         if(!isYuvBuffer(hnd)) {
    592             if(extOrient & HWC_TRANSFORM_ROT_90) {
    593                 int dstWidth = ctx->dpyAttr[dpy].xres;
    594                 int dstHeight = ctx->dpyAttr[dpy].yres;;
    595                 int srcWidth = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres;
    596                 int srcHeight = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres;
    597                 if(!isPrimaryPortrait(ctx)) {
    598                     swap(srcWidth, srcHeight);
    599                 }                    // Get Aspect Ratio for external
    600                 getAspectRatioPosition(dstWidth, dstHeight, srcWidth,
    601                                     srcHeight, displayFrame);
    602                 // Crop - this is needed, because for sidesync, the dest fb will
    603                 // be in portrait orientation, so update the crop to not show the
    604                 // black side bands.
    605                 if (isOrientationPortrait(ctx)) {
    606                     sourceCrop = displayFrame;
    607                     displayFrame.left = 0;
    608                     displayFrame.top = 0;
    609                     displayFrame.right = dstWidth;
    610                     displayFrame.bottom = dstHeight;
    611                 }
    612             }
    613             if(ctx->dpyAttr[dpy].mDownScaleMode) {
    614                 int extW, extH;
    615                 // if downscale is enabled, map the co-ordinates to new
    616                 // domain(downscaled)
    617                 float fbWidth  = (float)ctx->dpyAttr[dpy].xres;
    618                 float fbHeight = (float)ctx->dpyAttr[dpy].yres;
    619                 // query MDP configured attributes
    620                 if(dpy == HWC_DISPLAY_EXTERNAL)
    621                     ctx->mExtDisplay->getAttributes(extW, extH);
    622                 else
    623                     ctx->mVirtualDisplay->getAttributes(extW, extH);
    624                 //Calculate the ratio...
    625                 float wRatio = ((float)extW)/fbWidth;
    626                 float hRatio = ((float)extH)/fbHeight;
    627 
    628                 //convert Dim to hwc_rect_t
    629                 displayFrame.left = int(wRatio*(float)displayFrame.left);
    630                 displayFrame.top = int(hRatio*(float)displayFrame.top);
    631                 displayFrame.right = int(wRatio*(float)displayFrame.right);
    632                 displayFrame.bottom = int(hRatio*(float)displayFrame.bottom);
    633             }
    634         }else {
    635             if(extOrient || ctx->dpyAttr[dpy].mDownScaleMode) {
    636                 getAspectRatioPosition(ctx, dpy, extOrient,
    637                                        displayFrame, displayFrame);
    638             }
    639         }
    640         // If there is a external orientation set, use that
    641         if(extOrient) {
    642             transform = extOrient;
    643             orient = static_cast<ovutils::eTransform >(extOrient);
    644         }
    645         // Calculate the actionsafe dimensions for External(dpy = 1 or 2)
    646         getActionSafePosition(ctx, dpy, displayFrame);
    647     }
    648 }
    649 
    650 /* Returns the orientation which needs to be set on External for
    651  *  SideSync/Buffer Mirrormode
    652  */
    653 int getMirrorModeOrientation(hwc_context_t *ctx) {
    654     int extOrientation = 0;
    655     int deviceOrientation = ctx->deviceOrientation;
    656     if(!isPrimaryPortrait(ctx))
    657         deviceOrientation = (deviceOrientation + 1) % 4;
    658      if (deviceOrientation == 0)
    659          extOrientation = HWC_TRANSFORM_ROT_270;
    660      else if (deviceOrientation == 1)//90
    661          extOrientation = 0;
    662      else if (deviceOrientation == 2)//180
    663          extOrientation = HWC_TRANSFORM_ROT_90;
    664      else if (deviceOrientation == 3)//270
    665          extOrientation = HWC_TRANSFORM_FLIP_V | HWC_TRANSFORM_FLIP_H;
    666 
    667     return extOrientation;
    668 }
    669 
    670 /* Get External State names */
    671 const char* getExternalDisplayState(uint32_t external_state) {
    672     static const char* externalStates[EXTERNAL_MAXSTATES] = {0};
    673     externalStates[EXTERNAL_OFFLINE] = STR(EXTERNAL_OFFLINE);
    674     externalStates[EXTERNAL_ONLINE]  = STR(EXTERNAL_ONLINE);
    675     externalStates[EXTERNAL_PAUSE]   = STR(EXTERNAL_PAUSE);
    676     externalStates[EXTERNAL_RESUME]  = STR(EXTERNAL_RESUME);
    677 
    678     if(external_state >= EXTERNAL_MAXSTATES) {
    679         return "EXTERNAL_INVALID";
    680     }
    681 
    682     return externalStates[external_state];
    683 }
    684 
    685 bool isDownscaleRequired(hwc_layer_1_t const* layer) {
    686     hwc_rect_t displayFrame  = layer->displayFrame;
    687     hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf);
    688     int dst_w, dst_h, src_w, src_h;
    689     dst_w = displayFrame.right - displayFrame.left;
    690     dst_h = displayFrame.bottom - displayFrame.top;
    691     src_w = sourceCrop.right - sourceCrop.left;
    692     src_h = sourceCrop.bottom - sourceCrop.top;
    693 
    694     if(((src_w > dst_w) || (src_h > dst_h)))
    695         return true;
    696 
    697     return false;
    698 }
    699 bool needsScaling(hwc_layer_1_t const* layer) {
    700     int dst_w, dst_h, src_w, src_h;
    701     hwc_rect_t displayFrame  = layer->displayFrame;
    702     hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf);
    703 
    704     dst_w = displayFrame.right - displayFrame.left;
    705     dst_h = displayFrame.bottom - displayFrame.top;
    706     src_w = sourceCrop.right - sourceCrop.left;
    707     src_h = sourceCrop.bottom - sourceCrop.top;
    708 
    709     if(((src_w != dst_w) || (src_h != dst_h)))
    710         return true;
    711 
    712     return false;
    713 }
    714 
    715 // Checks if layer needs scaling with split
    716 bool needsScalingWithSplit(hwc_context_t* ctx, hwc_layer_1_t const* layer,
    717         const int& dpy) {
    718 
    719     int src_width_l, src_height_l;
    720     int src_width_r, src_height_r;
    721     int dst_width_l, dst_height_l;
    722     int dst_width_r, dst_height_r;
    723     int hw_w = ctx->dpyAttr[dpy].xres;
    724     int hw_h = ctx->dpyAttr[dpy].yres;
    725     hwc_rect_t cropL, dstL, cropR, dstR;
    726     const int lSplit = getLeftSplit(ctx, dpy);
    727     hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf);
    728     hwc_rect_t displayFrame  = layer->displayFrame;
    729     private_handle_t *hnd = (private_handle_t *)layer->handle;
    730 
    731     cropL = sourceCrop;
    732     dstL = displayFrame;
    733     hwc_rect_t scissorL = { 0, 0, lSplit, hw_h };
    734     scissorL = getIntersection(ctx->mViewFrame[dpy], scissorL);
    735     qhwc::calculate_crop_rects(cropL, dstL, scissorL, 0);
    736 
    737     cropR = sourceCrop;
    738     dstR = displayFrame;
    739     hwc_rect_t scissorR = { lSplit, 0, hw_w, hw_h };
    740     scissorR = getIntersection(ctx->mViewFrame[dpy], scissorR);
    741     qhwc::calculate_crop_rects(cropR, dstR, scissorR, 0);
    742 
    743     // Sanitize Crop to stitch
    744     sanitizeSourceCrop(cropL, cropR, hnd);
    745 
    746     // Calculate the left dst
    747     dst_width_l = dstL.right - dstL.left;
    748     dst_height_l = dstL.bottom - dstL.top;
    749     src_width_l = cropL.right - cropL.left;
    750     src_height_l = cropL.bottom - cropL.top;
    751 
    752     // check if there is any scaling on the left
    753     if(((src_width_l != dst_width_l) || (src_height_l != dst_height_l)))
    754         return true;
    755 
    756     // Calculate the right dst
    757     dst_width_r = dstR.right - dstR.left;
    758     dst_height_r = dstR.bottom - dstR.top;
    759     src_width_r = cropR.right - cropR.left;
    760     src_height_r = cropR.bottom - cropR.top;
    761 
    762     // check if there is any scaling on the right
    763     if(((src_width_r != dst_width_r) || (src_height_r != dst_height_r)))
    764         return true;
    765 
    766     return false;
    767 }
    768 
    769 bool isAlphaScaled(hwc_layer_1_t const* layer) {
    770     if(needsScaling(layer) && isAlphaPresent(layer)) {
    771         return true;
    772     }
    773     return false;
    774 }
    775 
    776 bool isAlphaPresent(hwc_layer_1_t const* layer) {
    777     private_handle_t *hnd = (private_handle_t *)layer->handle;
    778     if(hnd) {
    779         int format = hnd->format;
    780         switch(format) {
    781         case HAL_PIXEL_FORMAT_RGBA_8888:
    782         case HAL_PIXEL_FORMAT_BGRA_8888:
    783             // In any more formats with Alpha go here..
    784             return true;
    785         default : return false;
    786         }
    787     }
    788     return false;
    789 }
    790 
    791 static void trimLayer(hwc_context_t *ctx, const int& dpy, const int& transform,
    792         hwc_rect_t& crop, hwc_rect_t& dst) {
    793     int hw_w = ctx->dpyAttr[dpy].xres;
    794     int hw_h = ctx->dpyAttr[dpy].yres;
    795     if(dst.left < 0 || dst.top < 0 ||
    796             dst.right > hw_w || dst.bottom > hw_h) {
    797         hwc_rect_t scissor = {0, 0, hw_w, hw_h };
    798         scissor = getIntersection(ctx->mViewFrame[dpy], scissor);
    799         qhwc::calculate_crop_rects(crop, dst, scissor, transform);
    800     }
    801 }
    802 
    803 static void trimList(hwc_context_t *ctx, hwc_display_contents_1_t *list,
    804         const int& dpy) {
    805     for(uint32_t i = 0; i < list->numHwLayers - 1; i++) {
    806         hwc_layer_1_t *layer = &list->hwLayers[i];
    807         hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
    808         trimLayer(ctx, dpy,
    809                 list->hwLayers[i].transform,
    810                 (hwc_rect_t&)crop,
    811                 (hwc_rect_t&)list->hwLayers[i].displayFrame);
    812         layer->sourceCropf.left = (float)crop.left;
    813         layer->sourceCropf.right = (float)crop.right;
    814         layer->sourceCropf.top = (float)crop.top;
    815         layer->sourceCropf.bottom = (float)crop.bottom;
    816     }
    817 }
    818 
    819 void setListStats(hwc_context_t *ctx,
    820         hwc_display_contents_1_t *list, int dpy) {
    821     const int prevYuvCount = ctx->listStats[dpy].yuvCount;
    822     memset(&ctx->listStats[dpy], 0, sizeof(ListStats));
    823     ctx->listStats[dpy].numAppLayers = (int)list->numHwLayers - 1;
    824     ctx->listStats[dpy].fbLayerIndex = (int)list->numHwLayers - 1;
    825     ctx->listStats[dpy].skipCount = 0;
    826     ctx->listStats[dpy].preMultipliedAlpha = false;
    827     ctx->listStats[dpy].isSecurePresent = false;
    828     ctx->listStats[dpy].yuvCount = 0;
    829     char property[PROPERTY_VALUE_MAX];
    830     ctx->listStats[dpy].extOnlyLayerIndex = -1;
    831     ctx->listStats[dpy].isDisplayAnimating = false;
    832     ctx->listStats[dpy].secureUI = false;
    833     ctx->listStats[dpy].yuv4k2kCount = 0;
    834     ctx->dpyAttr[dpy].mActionSafePresent = isActionSafePresent(ctx, dpy);
    835     ctx->listStats[dpy].renderBufIndexforABC = -1;
    836 
    837     resetROI(ctx, dpy);
    838 
    839     trimList(ctx, list, dpy);
    840     optimizeLayerRects(list);
    841     for (size_t i = 0; i < (size_t)ctx->listStats[dpy].numAppLayers; i++) {
    842         hwc_layer_1_t const* layer = &list->hwLayers[i];
    843         private_handle_t *hnd = (private_handle_t *)layer->handle;
    844 
    845 #ifdef QCOM_BSP
    846         if (layer->flags & HWC_SCREENSHOT_ANIMATOR_LAYER) {
    847             ctx->listStats[dpy].isDisplayAnimating = true;
    848         }
    849         if(isSecureDisplayBuffer(hnd)) {
    850             ctx->listStats[dpy].secureUI = true;
    851         }
    852 #endif
    853         // continue if number of app layers exceeds MAX_NUM_APP_LAYERS
    854         if(ctx->listStats[dpy].numAppLayers > MAX_NUM_APP_LAYERS)
    855             continue;
    856 
    857         //reset yuv indices
    858         ctx->listStats[dpy].yuvIndices[i] = -1;
    859         ctx->listStats[dpy].yuv4k2kIndices[i] = -1;
    860 
    861         if (isSecureBuffer(hnd)) {
    862             ctx->listStats[dpy].isSecurePresent = true;
    863         }
    864 
    865         if (isSkipLayer(&list->hwLayers[i])) {
    866             ctx->listStats[dpy].skipCount++;
    867         }
    868 
    869         if (UNLIKELY(isYuvBuffer(hnd))) {
    870             int& yuvCount = ctx->listStats[dpy].yuvCount;
    871             ctx->listStats[dpy].yuvIndices[yuvCount] = (int)i;
    872             yuvCount++;
    873 
    874             if(UNLIKELY(is4kx2kYuvBuffer(hnd))){
    875                 int& yuv4k2kCount = ctx->listStats[dpy].yuv4k2kCount;
    876                 ctx->listStats[dpy].yuv4k2kIndices[yuv4k2kCount] = (int)i;
    877                 yuv4k2kCount++;
    878             }
    879         }
    880         if(layer->blending == HWC_BLENDING_PREMULT)
    881             ctx->listStats[dpy].preMultipliedAlpha = true;
    882 
    883 
    884         if(UNLIKELY(isExtOnly(hnd))){
    885             ctx->listStats[dpy].extOnlyLayerIndex = (int)i;
    886         }
    887     }
    888     if(ctx->listStats[dpy].yuvCount > 0) {
    889         if (property_get("hw.cabl.yuv", property, NULL) > 0) {
    890             if (atoi(property) != 1) {
    891                 property_set("hw.cabl.yuv", "1");
    892             }
    893         }
    894     } else {
    895         if (property_get("hw.cabl.yuv", property, NULL) > 0) {
    896             if (atoi(property) != 0) {
    897                 property_set("hw.cabl.yuv", "0");
    898             }
    899         }
    900     }
    901 
    902     //The marking of video begin/end is useful on some targets where we need
    903     //to have a padding round to be able to shift pipes across mixers.
    904     if(prevYuvCount != ctx->listStats[dpy].yuvCount) {
    905         ctx->mVideoTransFlag = true;
    906     }
    907 
    908     if(dpy == HWC_DISPLAY_PRIMARY) {
    909         ctx->mAD->markDoable(ctx, list);
    910     }
    911 }
    912 
    913 
    914 static void calc_cut(double& leftCutRatio, double& topCutRatio,
    915         double& rightCutRatio, double& bottomCutRatio, int orient) {
    916     if(orient & HAL_TRANSFORM_FLIP_H) {
    917         swap(leftCutRatio, rightCutRatio);
    918     }
    919     if(orient & HAL_TRANSFORM_FLIP_V) {
    920         swap(topCutRatio, bottomCutRatio);
    921     }
    922     if(orient & HAL_TRANSFORM_ROT_90) {
    923         //Anti clock swapping
    924         double tmpCutRatio = leftCutRatio;
    925         leftCutRatio = topCutRatio;
    926         topCutRatio = rightCutRatio;
    927         rightCutRatio = bottomCutRatio;
    928         bottomCutRatio = tmpCutRatio;
    929     }
    930 }
    931 
    932 bool isSecuring(hwc_context_t* ctx, hwc_layer_1_t const* layer) {
    933     if((ctx->mMDP.version < qdutils::MDSS_V5) &&
    934        (ctx->mMDP.version > qdutils::MDP_V3_0) &&
    935         ctx->mSecuring) {
    936         return true;
    937     }
    938     if (isSecureModePolicy(ctx->mMDP.version)) {
    939         private_handle_t *hnd = (private_handle_t *)layer->handle;
    940         if(ctx->mSecureMode) {
    941             if (! isSecureBuffer(hnd)) {
    942                 ALOGD_IF(HWC_UTILS_DEBUG,"%s:Securing Turning ON ...",
    943                          __FUNCTION__);
    944                 return true;
    945             }
    946         } else {
    947             if (isSecureBuffer(hnd)) {
    948                 ALOGD_IF(HWC_UTILS_DEBUG,"%s:Securing Turning OFF ...",
    949                          __FUNCTION__);
    950                 return true;
    951             }
    952         }
    953     }
    954     return false;
    955 }
    956 
    957 bool isSecureModePolicy(int mdpVersion) {
    958     if (mdpVersion < qdutils::MDSS_V5)
    959         return true;
    960     else
    961         return false;
    962 }
    963 
    964 bool isRotatorSupportedFormat(private_handle_t *hnd) {
    965     // Following rotator src formats are supported by mdp driver
    966     // TODO: Add more formats in future, if mdp driver adds support
    967     switch(hnd->format) {
    968         case HAL_PIXEL_FORMAT_RGBA_8888:
    969         case HAL_PIXEL_FORMAT_RGBX_8888:
    970         case HAL_PIXEL_FORMAT_RGB_565:
    971         case HAL_PIXEL_FORMAT_RGB_888:
    972         case HAL_PIXEL_FORMAT_BGRA_8888:
    973             return true;
    974         default:
    975             return false;
    976     }
    977     return false;
    978 }
    979 
    980 bool isRotationDoable(hwc_context_t *ctx, private_handle_t *hnd) {
    981     // Rotate layers, if it is YUV type or rendered by CPU and not
    982     // for the MDP versions below MDP5
    983     if((isCPURendered(hnd) && isRotatorSupportedFormat(hnd) &&
    984         !ctx->mMDP.version < qdutils::MDSS_V5)
    985                    || isYuvBuffer(hnd)) {
    986         return true;
    987     }
    988     return false;
    989 }
    990 
    991 // returns true if Action safe dimensions are set and target supports Actionsafe
    992 bool isActionSafePresent(hwc_context_t *ctx, int dpy) {
    993     // if external supports underscan, do nothing
    994     // it will be taken care in the driver
    995     // Disable Action safe for 8974 due to HW limitation for downscaling
    996     // layers with overlapped region
    997     // Disable Actionsafe for non HDMI displays.
    998     if(!(dpy == HWC_DISPLAY_EXTERNAL) ||
    999         qdutils::MDPVersion::getInstance().is8x74v2() ||
   1000         ctx->mExtDisplay->isCEUnderscanSupported()) {
   1001         return false;
   1002     }
   1003 
   1004     char value[PROPERTY_VALUE_MAX];
   1005     // Read action safe properties
   1006     property_get("persist.sys.actionsafe.width", value, "0");
   1007     ctx->dpyAttr[dpy].mAsWidthRatio = atoi(value);
   1008     property_get("persist.sys.actionsafe.height", value, "0");
   1009     ctx->dpyAttr[dpy].mAsHeightRatio = atoi(value);
   1010 
   1011     if(!ctx->dpyAttr[dpy].mAsWidthRatio && !ctx->dpyAttr[dpy].mAsHeightRatio) {
   1012         //No action safe ratio set, return
   1013         return false;
   1014     }
   1015     return true;
   1016 }
   1017 
   1018 int getBlending(int blending) {
   1019     switch(blending) {
   1020     case HWC_BLENDING_NONE:
   1021         return overlay::utils::OVERLAY_BLENDING_OPAQUE;
   1022     case HWC_BLENDING_PREMULT:
   1023         return overlay::utils::OVERLAY_BLENDING_PREMULT;
   1024     case HWC_BLENDING_COVERAGE :
   1025     default:
   1026         return overlay::utils::OVERLAY_BLENDING_COVERAGE;
   1027     }
   1028 }
   1029 
   1030 //Crops source buffer against destination and FB boundaries
   1031 void calculate_crop_rects(hwc_rect_t& crop, hwc_rect_t& dst,
   1032                           const hwc_rect_t& scissor, int orient) {
   1033 
   1034     int& crop_l = crop.left;
   1035     int& crop_t = crop.top;
   1036     int& crop_r = crop.right;
   1037     int& crop_b = crop.bottom;
   1038     int crop_w = crop.right - crop.left;
   1039     int crop_h = crop.bottom - crop.top;
   1040 
   1041     int& dst_l = dst.left;
   1042     int& dst_t = dst.top;
   1043     int& dst_r = dst.right;
   1044     int& dst_b = dst.bottom;
   1045     int dst_w = abs(dst.right - dst.left);
   1046     int dst_h = abs(dst.bottom - dst.top);
   1047 
   1048     const int& sci_l = scissor.left;
   1049     const int& sci_t = scissor.top;
   1050     const int& sci_r = scissor.right;
   1051     const int& sci_b = scissor.bottom;
   1052 
   1053     double leftCutRatio = 0.0, rightCutRatio = 0.0, topCutRatio = 0.0,
   1054             bottomCutRatio = 0.0;
   1055 
   1056     if(dst_l < sci_l) {
   1057         leftCutRatio = (double)(sci_l - dst_l) / (double)dst_w;
   1058         dst_l = sci_l;
   1059     }
   1060 
   1061     if(dst_r > sci_r) {
   1062         rightCutRatio = (double)(dst_r - sci_r) / (double)dst_w;
   1063         dst_r = sci_r;
   1064     }
   1065 
   1066     if(dst_t < sci_t) {
   1067         topCutRatio = (double)(sci_t - dst_t) / (double)dst_h;
   1068         dst_t = sci_t;
   1069     }
   1070 
   1071     if(dst_b > sci_b) {
   1072         bottomCutRatio = (double)(dst_b - sci_b) / (double)dst_h;
   1073         dst_b = sci_b;
   1074     }
   1075 
   1076     calc_cut(leftCutRatio, topCutRatio, rightCutRatio, bottomCutRatio, orient);
   1077     crop_l += (int)round((double)crop_w * leftCutRatio);
   1078     crop_t += (int)round((double)crop_h * topCutRatio);
   1079     crop_r -= (int)round((double)crop_w * rightCutRatio);
   1080     crop_b -= (int)round((double)crop_h * bottomCutRatio);
   1081 }
   1082 
   1083 bool areLayersIntersecting(const hwc_layer_1_t* layer1,
   1084         const hwc_layer_1_t* layer2) {
   1085     hwc_rect_t irect = getIntersection(layer1->displayFrame,
   1086             layer2->displayFrame);
   1087     return isValidRect(irect);
   1088 }
   1089 
   1090 bool isSameRect(const hwc_rect& rect1, const hwc_rect& rect2)
   1091 {
   1092    return ((rect1.left == rect2.left) && (rect1.top == rect2.top) &&
   1093            (rect1.right == rect2.right) && (rect1.bottom == rect2.bottom));
   1094 }
   1095 
   1096 bool isValidRect(const hwc_rect& rect)
   1097 {
   1098    return ((rect.bottom > rect.top) && (rect.right > rect.left)) ;
   1099 }
   1100 
   1101 bool operator ==(const hwc_rect_t& lhs, const hwc_rect_t& rhs) {
   1102     if(lhs.left == rhs.left && lhs.top == rhs.top &&
   1103        lhs.right == rhs.right &&  lhs.bottom == rhs.bottom )
   1104           return true ;
   1105     return false;
   1106 }
   1107 
   1108 hwc_rect_t moveRect(const hwc_rect_t& rect, const int& x_off, const int& y_off)
   1109 {
   1110     hwc_rect_t res;
   1111 
   1112     if(!isValidRect(rect))
   1113         return (hwc_rect_t){0, 0, 0, 0};
   1114 
   1115     res.left = rect.left + x_off;
   1116     res.top = rect.top + y_off;
   1117     res.right = rect.right + x_off;
   1118     res.bottom = rect.bottom + y_off;
   1119 
   1120     return res;
   1121 }
   1122 
   1123 /* computes the intersection of two rects */
   1124 hwc_rect_t getIntersection(const hwc_rect_t& rect1, const hwc_rect_t& rect2)
   1125 {
   1126    hwc_rect_t res;
   1127 
   1128    if(!isValidRect(rect1) || !isValidRect(rect2)){
   1129       return (hwc_rect_t){0, 0, 0, 0};
   1130    }
   1131 
   1132 
   1133    res.left = max(rect1.left, rect2.left);
   1134    res.top = max(rect1.top, rect2.top);
   1135    res.right = min(rect1.right, rect2.right);
   1136    res.bottom = min(rect1.bottom, rect2.bottom);
   1137 
   1138    if(!isValidRect(res))
   1139       return (hwc_rect_t){0, 0, 0, 0};
   1140 
   1141    return res;
   1142 }
   1143 
   1144 /* computes the union of two rects */
   1145 hwc_rect_t getUnion(const hwc_rect &rect1, const hwc_rect &rect2)
   1146 {
   1147    hwc_rect_t res;
   1148 
   1149    if(!isValidRect(rect1)){
   1150       return rect2;
   1151    }
   1152 
   1153    if(!isValidRect(rect2)){
   1154       return rect1;
   1155    }
   1156 
   1157    res.left = min(rect1.left, rect2.left);
   1158    res.top = min(rect1.top, rect2.top);
   1159    res.right =  max(rect1.right, rect2.right);
   1160    res.bottom =  max(rect1.bottom, rect2.bottom);
   1161 
   1162    return res;
   1163 }
   1164 
   1165 /* Not a geometrical rect deduction. Deducts rect2 from rect1 only if it results
   1166  * a single rect */
   1167 hwc_rect_t deductRect(const hwc_rect_t& rect1, const hwc_rect_t& rect2) {
   1168 
   1169    hwc_rect_t res = rect1;
   1170 
   1171    if((rect1.left == rect2.left) && (rect1.right == rect2.right)) {
   1172       if((rect1.top == rect2.top) && (rect2.bottom <= rect1.bottom))
   1173          res.top = rect2.bottom;
   1174       else if((rect1.bottom == rect2.bottom)&& (rect2.top >= rect1.top))
   1175          res.bottom = rect2.top;
   1176    }
   1177    else if((rect1.top == rect2.top) && (rect1.bottom == rect2.bottom)) {
   1178       if((rect1.left == rect2.left) && (rect2.right <= rect1.right))
   1179          res.left = rect2.right;
   1180       else if((rect1.right == rect2.right)&& (rect2.left >= rect1.left))
   1181          res.right = rect2.left;
   1182    }
   1183    return res;
   1184 }
   1185 
   1186 void optimizeLayerRects(const hwc_display_contents_1_t *list) {
   1187     int i= (int)list->numHwLayers-2;
   1188     while(i > 0) {
   1189         //see if there is no blending required.
   1190         //If it is opaque see if we can substract this region from below
   1191         //layers.
   1192         if(list->hwLayers[i].blending == HWC_BLENDING_NONE) {
   1193             int j= i-1;
   1194             hwc_rect_t& topframe =
   1195                 (hwc_rect_t&)list->hwLayers[i].displayFrame;
   1196             while(j >= 0) {
   1197                if(!needsScaling(&list->hwLayers[j])) {
   1198                   hwc_layer_1_t* layer = (hwc_layer_1_t*)&list->hwLayers[j];
   1199                   hwc_rect_t& bottomframe = layer->displayFrame;
   1200                   hwc_rect_t bottomCrop =
   1201                       integerizeSourceCrop(layer->sourceCropf);
   1202                   int transform =layer->transform;
   1203 
   1204                   hwc_rect_t irect = getIntersection(bottomframe, topframe);
   1205                   if(isValidRect(irect)) {
   1206                      hwc_rect_t dest_rect;
   1207                      //if intersection is valid rect, deduct it
   1208                      dest_rect  = deductRect(bottomframe, irect);
   1209                      qhwc::calculate_crop_rects(bottomCrop, bottomframe,
   1210                                                 dest_rect, transform);
   1211                      //Update layer sourceCropf
   1212                      layer->sourceCropf.left =(float)bottomCrop.left;
   1213                      layer->sourceCropf.top = (float)bottomCrop.top;
   1214                      layer->sourceCropf.right = (float)bottomCrop.right;
   1215                      layer->sourceCropf.bottom = (float)bottomCrop.bottom;
   1216 #ifdef QCOM_BSP
   1217                      //Update layer dirtyRect
   1218                      layer->dirtyRect = getIntersection(bottomCrop,
   1219                                             layer->dirtyRect);
   1220 #endif
   1221                   }
   1222                }
   1223                j--;
   1224             }
   1225         }
   1226         i--;
   1227     }
   1228 }
   1229 
   1230 void getNonWormholeRegion(hwc_display_contents_1_t* list,
   1231                               hwc_rect_t& nwr)
   1232 {
   1233     size_t last = list->numHwLayers - 1;
   1234     hwc_rect_t fbDisplayFrame = list->hwLayers[last].displayFrame;
   1235     //Initiliaze nwr to first frame
   1236     nwr.left =  list->hwLayers[0].displayFrame.left;
   1237     nwr.top =  list->hwLayers[0].displayFrame.top;
   1238     nwr.right =  list->hwLayers[0].displayFrame.right;
   1239     nwr.bottom =  list->hwLayers[0].displayFrame.bottom;
   1240 
   1241     for (size_t i = 1; i < last; i++) {
   1242         hwc_rect_t displayFrame = list->hwLayers[i].displayFrame;
   1243         nwr = getUnion(nwr, displayFrame);
   1244     }
   1245 
   1246     //Intersect with the framebuffer
   1247     nwr = getIntersection(nwr, fbDisplayFrame);
   1248 }
   1249 
   1250 bool isExternalActive(hwc_context_t* ctx) {
   1251     return ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].isActive;
   1252 }
   1253 
   1254 void closeAcquireFds(hwc_display_contents_1_t* list) {
   1255     if(LIKELY(list)) {
   1256         for(uint32_t i = 0; i < list->numHwLayers; i++) {
   1257             //Close the acquireFenceFds
   1258             //HWC_FRAMEBUFFER are -1 already by SF, rest we close.
   1259             if(list->hwLayers[i].acquireFenceFd >= 0) {
   1260                 close(list->hwLayers[i].acquireFenceFd);
   1261                 list->hwLayers[i].acquireFenceFd = -1;
   1262             }
   1263         }
   1264         //Writeback
   1265         if(list->outbufAcquireFenceFd >= 0) {
   1266             close(list->outbufAcquireFenceFd);
   1267             list->outbufAcquireFenceFd = -1;
   1268         }
   1269     }
   1270 }
   1271 
   1272 int hwc_sync(hwc_context_t *ctx, hwc_display_contents_1_t* list, int dpy,
   1273         int fd) {
   1274     ATRACE_CALL();
   1275     int ret = 0;
   1276     int acquireFd[MAX_NUM_APP_LAYERS];
   1277     int count = 0;
   1278     int releaseFd = -1;
   1279     int retireFd = -1;
   1280     int fbFd = -1;
   1281     bool swapzero = false;
   1282 
   1283     struct mdp_buf_sync data;
   1284     memset(&data, 0, sizeof(data));
   1285     data.acq_fen_fd = acquireFd;
   1286     data.rel_fen_fd = &releaseFd;
   1287     data.retire_fen_fd = &retireFd;
   1288     data.flags = MDP_BUF_SYNC_FLAG_RETIRE_FENCE;
   1289 
   1290     char property[PROPERTY_VALUE_MAX];
   1291     if(property_get("debug.egl.swapinterval", property, "1") > 0) {
   1292         if(atoi(property) == 0)
   1293             swapzero = true;
   1294     }
   1295 
   1296     bool isExtAnimating = false;
   1297     if(dpy)
   1298        isExtAnimating = ctx->listStats[dpy].isDisplayAnimating;
   1299 
   1300     //Send acquireFenceFds to rotator
   1301     for(uint32_t i = 0; i < ctx->mLayerRotMap[dpy]->getCount(); i++) {
   1302         int rotFd = ctx->mRotMgr->getRotDevFd();
   1303         int rotReleaseFd = -1;
   1304         overlay::Rotator* currRot = ctx->mLayerRotMap[dpy]->getRot(i);
   1305         hwc_layer_1_t* currLayer = ctx->mLayerRotMap[dpy]->getLayer(i);
   1306         if((currRot == NULL) || (currLayer == NULL)) {
   1307             continue;
   1308         }
   1309         struct mdp_buf_sync rotData;
   1310         memset(&rotData, 0, sizeof(rotData));
   1311         rotData.acq_fen_fd =
   1312                 &currLayer->acquireFenceFd;
   1313         rotData.rel_fen_fd = &rotReleaseFd; //driver to populate this
   1314         rotData.session_id = currRot->getSessId();
   1315         if(currLayer->acquireFenceFd >= 0) {
   1316             rotData.acq_fen_fd_cnt = 1; //1 ioctl call per rot session
   1317         }
   1318         int ret = 0;
   1319         ret = ioctl(rotFd, MSMFB_BUFFER_SYNC, &rotData);
   1320         if(ret < 0) {
   1321             ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed for rot sync, err=%s",
   1322                     __FUNCTION__, strerror(errno));
   1323             close(rotReleaseFd);
   1324         } else {
   1325             close(currLayer->acquireFenceFd);
   1326             //For MDP to wait on.
   1327             currLayer->acquireFenceFd =
   1328                     dup(rotReleaseFd);
   1329             //A buffer is free to be used by producer as soon as its copied to
   1330             //rotator
   1331             currLayer->releaseFenceFd =
   1332                     rotReleaseFd;
   1333         }
   1334     }
   1335 
   1336     //Accumulate acquireFenceFds for MDP Overlays
   1337     if(list->outbufAcquireFenceFd >= 0) {
   1338         //Writeback output buffer
   1339         acquireFd[count++] = list->outbufAcquireFenceFd;
   1340     }
   1341 
   1342     for(uint32_t i = 0; i < list->numHwLayers; i++) {
   1343         if(((isAbcInUse(ctx)== true ) ||
   1344           (list->hwLayers[i].compositionType == HWC_OVERLAY)) &&
   1345                         list->hwLayers[i].acquireFenceFd >= 0) {
   1346             if(UNLIKELY(swapzero))
   1347                 acquireFd[count++] = -1;
   1348             // if ABC is enabled for more than one layer.
   1349             // renderBufIndexforABC will work as FB.Hence
   1350             // set the acquireFD from fd - which is coming from copybit
   1351             else if(fd >= 0 && (isAbcInUse(ctx) == true)) {
   1352                 if(ctx->listStats[dpy].renderBufIndexforABC ==(int32_t)i)
   1353                    acquireFd[count++] = fd;
   1354                 else
   1355                    continue;
   1356             } else
   1357                 acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
   1358         }
   1359         if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
   1360             if(UNLIKELY(swapzero))
   1361                 acquireFd[count++] = -1;
   1362             else if(fd >= 0) {
   1363                 //set the acquireFD from fd - which is coming from c2d
   1364                 acquireFd[count++] = fd;
   1365                 // Buffer sync IOCTL should be async when using c2d fence is
   1366                 // used
   1367                 data.flags &= ~MDP_BUF_SYNC_FLAG_WAIT;
   1368             } else if(list->hwLayers[i].acquireFenceFd >= 0)
   1369                 acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
   1370         }
   1371     }
   1372 
   1373     if ((fd >= 0) && !dpy && ctx->mPtorInfo.isActive()) {
   1374         // Acquire c2d fence of Overlap render buffer
   1375         acquireFd[count++] = fd;
   1376     }
   1377 
   1378     data.acq_fen_fd_cnt = count;
   1379     fbFd = ctx->dpyAttr[dpy].fd;
   1380 
   1381     //Waits for acquire fences, returns a release fence
   1382     if(LIKELY(!swapzero)) {
   1383         ret = ioctl(fbFd, MSMFB_BUFFER_SYNC, &data);
   1384     }
   1385 
   1386     if(ret < 0) {
   1387         ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed, err=%s",
   1388                   __FUNCTION__, strerror(errno));
   1389         ALOGE("%s: acq_fen_fd_cnt=%d flags=%d fd=%d dpy=%d numHwLayers=%zu",
   1390               __FUNCTION__, data.acq_fen_fd_cnt, data.flags, fbFd,
   1391               dpy, list->numHwLayers);
   1392         close(releaseFd);
   1393         releaseFd = -1;
   1394         close(retireFd);
   1395         retireFd = -1;
   1396     }
   1397 
   1398     for(uint32_t i = 0; i < list->numHwLayers; i++) {
   1399         if(list->hwLayers[i].compositionType == HWC_OVERLAY ||
   1400 #ifdef QCOM_BSP
   1401            list->hwLayers[i].compositionType == HWC_BLIT ||
   1402 #endif
   1403            list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
   1404             //Populate releaseFenceFds.
   1405             if(UNLIKELY(swapzero)) {
   1406                 list->hwLayers[i].releaseFenceFd = -1;
   1407             } else if(isExtAnimating) {
   1408                 // Release all the app layer fds immediately,
   1409                 // if animation is in progress.
   1410                 list->hwLayers[i].releaseFenceFd = -1;
   1411             } else if(list->hwLayers[i].releaseFenceFd < 0 ) {
   1412 #ifdef QCOM_BSP
   1413                 //If rotator has not already populated this field
   1414                 // & if it's a not VPU layer
   1415 
   1416                 // if ABC is enabled for more than one layer
   1417                 if(fd >= 0 && (isAbcInUse(ctx) == true) &&
   1418                   ctx->listStats[dpy].renderBufIndexforABC !=(int32_t)i){
   1419                     list->hwLayers[i].releaseFenceFd = dup(fd);
   1420                 } else if((list->hwLayers[i].compositionType == HWC_BLIT)&&
   1421                                                (isAbcInUse(ctx) == false)){
   1422                     //For Blit, the app layers should be released when the Blit
   1423                     //is complete. This fd was passed from copybit->draw
   1424                     list->hwLayers[i].releaseFenceFd = dup(fd);
   1425                 } else
   1426 #endif
   1427                 {
   1428                     list->hwLayers[i].releaseFenceFd = dup(releaseFd);
   1429                 }
   1430             }
   1431         }
   1432     }
   1433 
   1434     if(fd >= 0) {
   1435         close(fd);
   1436         fd = -1;
   1437     }
   1438 
   1439     if (!dpy && ctx->mCopyBit[dpy]) {
   1440         if (ctx->mPtorInfo.isActive())
   1441             ctx->mCopyBit[dpy]->setReleaseFdSync(releaseFd);
   1442         else
   1443             ctx->mCopyBit[dpy]->setReleaseFd(releaseFd);
   1444     }
   1445 
   1446     //Signals when MDP finishes reading rotator buffers.
   1447     ctx->mLayerRotMap[dpy]->setReleaseFd(releaseFd);
   1448     close(releaseFd);
   1449     releaseFd = -1;
   1450 
   1451     if(UNLIKELY(swapzero)) {
   1452         list->retireFenceFd = -1;
   1453     } else {
   1454         list->retireFenceFd = retireFd;
   1455     }
   1456     return ret;
   1457 }
   1458 
   1459 void setMdpFlags(hwc_context_t *ctx, hwc_layer_1_t *layer,
   1460         ovutils::eMdpFlags &mdpFlags,
   1461         int rotDownscale, int transform) {
   1462     private_handle_t *hnd = (private_handle_t *)layer->handle;
   1463     MetaData_t *metadata = hnd ? (MetaData_t *)hnd->base_metadata : NULL;
   1464 
   1465     if(layer->blending == HWC_BLENDING_PREMULT) {
   1466         ovutils::setMdpFlags(mdpFlags,
   1467                 ovutils::OV_MDP_BLEND_FG_PREMULT);
   1468     }
   1469 
   1470     if(isYuvBuffer(hnd)) {
   1471         if(isSecureBuffer(hnd)) {
   1472             ovutils::setMdpFlags(mdpFlags,
   1473                     ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
   1474         }
   1475         if(metadata && (metadata->operation & PP_PARAM_INTERLACED) &&
   1476                 metadata->interlaced) {
   1477             ovutils::setMdpFlags(mdpFlags,
   1478                     ovutils::OV_MDP_DEINTERLACE);
   1479         }
   1480     }
   1481 
   1482     if(isSecureDisplayBuffer(hnd)) {
   1483         // Secure display needs both SECURE_OVERLAY and SECURE_DISPLAY_OV
   1484         ovutils::setMdpFlags(mdpFlags,
   1485                              ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
   1486         ovutils::setMdpFlags(mdpFlags,
   1487                              ovutils::OV_MDP_SECURE_DISPLAY_OVERLAY_SESSION);
   1488     }
   1489 
   1490     //Pre-rotation will be used using rotator.
   1491     if(has90Transform(layer) && isRotationDoable(ctx, hnd)) {
   1492         ovutils::setMdpFlags(mdpFlags,
   1493                 ovutils::OV_MDP_SOURCE_ROTATED_90);
   1494     }
   1495     //No 90 component and no rot-downscale then flips done by MDP
   1496     //If we use rot then it might as well do flips
   1497     if(!(transform & HWC_TRANSFORM_ROT_90) && !rotDownscale) {
   1498         if(transform & HWC_TRANSFORM_FLIP_H) {
   1499             ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_FLIP_H);
   1500         }
   1501 
   1502         if(transform & HWC_TRANSFORM_FLIP_V) {
   1503             ovutils::setMdpFlags(mdpFlags,  ovutils::OV_MDP_FLIP_V);
   1504         }
   1505     }
   1506 
   1507     if(metadata &&
   1508         ((metadata->operation & PP_PARAM_HSIC)
   1509         || (metadata->operation & PP_PARAM_IGC)
   1510         || (metadata->operation & PP_PARAM_SHARP2))) {
   1511         ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_PP_EN);
   1512     }
   1513 }
   1514 
   1515 int configRotator(Rotator *rot, Whf& whf,
   1516         hwc_rect_t& crop, const eMdpFlags& mdpFlags,
   1517         const eTransform& orient, const int& downscale) {
   1518 
   1519     // Fix alignments for TILED format
   1520     if(whf.format == MDP_Y_CRCB_H2V2_TILE ||
   1521                             whf.format == MDP_Y_CBCR_H2V2_TILE) {
   1522         whf.w =  utils::alignup(whf.w, 64);
   1523         whf.h = utils::alignup(whf.h, 32);
   1524     }
   1525     rot->setSource(whf);
   1526 
   1527     if (qdutils::MDPVersion::getInstance().getMDPVersion() >=
   1528         qdutils::MDSS_V5) {
   1529          Dim rotCrop(crop.left, crop.top, crop.right - crop.left,
   1530                 crop.bottom - crop.top);
   1531         rot->setCrop(rotCrop);
   1532     }
   1533 
   1534     rot->setFlags(mdpFlags);
   1535     rot->setTransform(orient);
   1536     rot->setDownscale(downscale);
   1537     if(!rot->commit()) return -1;
   1538     return 0;
   1539 }
   1540 
   1541 int configMdp(Overlay *ov, const PipeArgs& parg,
   1542         const eTransform& orient, const hwc_rect_t& crop,
   1543         const hwc_rect_t& pos, const MetaData_t *metadata,
   1544         const eDest& dest) {
   1545     ov->setSource(parg, dest);
   1546     ov->setTransform(orient, dest);
   1547 
   1548     int crop_w = crop.right - crop.left;
   1549     int crop_h = crop.bottom - crop.top;
   1550     Dim dcrop(crop.left, crop.top, crop_w, crop_h);
   1551     ov->setCrop(dcrop, dest);
   1552 
   1553     int posW = pos.right - pos.left;
   1554     int posH = pos.bottom - pos.top;
   1555     Dim position(pos.left, pos.top, posW, posH);
   1556     ov->setPosition(position, dest);
   1557 
   1558     if (metadata)
   1559         ov->setVisualParams(*metadata, dest);
   1560 
   1561     if (!ov->commit(dest)) {
   1562         return -1;
   1563     }
   1564     return 0;
   1565 }
   1566 
   1567 int configColorLayer(hwc_context_t *ctx, hwc_layer_1_t *layer,
   1568         const int& dpy, eMdpFlags& mdpFlags, eZorder& z,
   1569         eIsFg& isFg, const eDest& dest) {
   1570 
   1571     hwc_rect_t dst = layer->displayFrame;
   1572     trimLayer(ctx, dpy, 0, dst, dst);
   1573 
   1574     int w = ctx->dpyAttr[dpy].xres;
   1575     int h = ctx->dpyAttr[dpy].yres;
   1576     int dst_w = dst.right - dst.left;
   1577     int dst_h = dst.bottom - dst.top;
   1578     uint32_t color = layer->transform;
   1579     Whf whf(w, h, getMdpFormat(HAL_PIXEL_FORMAT_RGBA_8888), 0);
   1580 
   1581     ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_SOLID_FILL);
   1582     if (layer->blending == HWC_BLENDING_PREMULT)
   1583         ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_BLEND_FG_PREMULT);
   1584 
   1585     PipeArgs parg(mdpFlags, whf, z, isFg, static_cast<eRotFlags>(0),
   1586                   layer->planeAlpha,
   1587                   (ovutils::eBlending) getBlending(layer->blending));
   1588 
   1589     // Configure MDP pipe for Color layer
   1590     Dim pos(dst.left, dst.top, dst_w, dst_h);
   1591     ctx->mOverlay->setSource(parg, dest);
   1592     ctx->mOverlay->setColor(color, dest);
   1593     ctx->mOverlay->setTransform(0, dest);
   1594     ctx->mOverlay->setCrop(pos, dest);
   1595     ctx->mOverlay->setPosition(pos, dest);
   1596 
   1597     if (!ctx->mOverlay->commit(dest)) {
   1598         ALOGE("%s: Configure color layer failed!", __FUNCTION__);
   1599         return -1;
   1600     }
   1601     return 0;
   1602 }
   1603 
   1604 void updateSource(eTransform& orient, Whf& whf,
   1605         hwc_rect_t& crop, Rotator *rot) {
   1606     Dim transformedCrop(crop.left, crop.top,
   1607             crop.right - crop.left,
   1608             crop.bottom - crop.top);
   1609     if (qdutils::MDPVersion::getInstance().getMDPVersion() >=
   1610         qdutils::MDSS_V5) {
   1611         //B-family rotator internally could modify destination dimensions if
   1612         //downscaling is supported
   1613         whf = rot->getDstWhf();
   1614         transformedCrop = rot->getDstDimensions();
   1615     } else {
   1616         //A-family rotator rotates entire buffer irrespective of crop, forcing
   1617         //us to recompute the crop based on transform
   1618         orient = static_cast<eTransform>(ovutils::getMdpOrient(orient));
   1619         preRotateSource(orient, whf, transformedCrop);
   1620     }
   1621 
   1622     crop.left = transformedCrop.x;
   1623     crop.top = transformedCrop.y;
   1624     crop.right = transformedCrop.x + transformedCrop.w;
   1625     crop.bottom = transformedCrop.y + transformedCrop.h;
   1626 }
   1627 
   1628 int configureNonSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
   1629         const int& dpy, eMdpFlags& mdpFlags, eZorder& z,
   1630         eIsFg& isFg, const eDest& dest, Rotator **rot) {
   1631 
   1632     private_handle_t *hnd = (private_handle_t *)layer->handle;
   1633 
   1634     if(!hnd) {
   1635         if (layer->flags & HWC_COLOR_FILL) {
   1636             // Configure Color layer
   1637             return configColorLayer(ctx, layer, dpy, mdpFlags, z, isFg, dest);
   1638         }
   1639         ALOGE("%s: layer handle is NULL", __FUNCTION__);
   1640         return -1;
   1641     }
   1642 
   1643     MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
   1644 
   1645     hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
   1646     hwc_rect_t dst = layer->displayFrame;
   1647     int transform = layer->transform;
   1648     eTransform orient = static_cast<eTransform>(transform);
   1649     int downscale = 0;
   1650     int rotFlags = ovutils::ROT_FLAGS_NONE;
   1651     uint32_t format = ovutils::getMdpFormat(hnd->format, isTileRendered(hnd));
   1652     Whf whf(getWidth(hnd), getHeight(hnd), format, (uint32_t)hnd->size);
   1653 
   1654     // Handle R/B swap
   1655     if (layer->flags & HWC_FORMAT_RB_SWAP) {
   1656         if (hnd->format == HAL_PIXEL_FORMAT_RGBA_8888)
   1657             whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRA_8888);
   1658         else if (hnd->format == HAL_PIXEL_FORMAT_RGBX_8888)
   1659             whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRX_8888);
   1660     }
   1661 
   1662     calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient);
   1663 
   1664     if(isYuvBuffer(hnd) && ctx->mMDP.version >= qdutils::MDP_V4_2 &&
   1665        ctx->mMDP.version < qdutils::MDSS_V5) {
   1666         downscale =  getDownscaleFactor(
   1667             crop.right - crop.left,
   1668             crop.bottom - crop.top,
   1669             dst.right - dst.left,
   1670             dst.bottom - dst.top);
   1671         if(downscale) {
   1672             rotFlags = ROT_DOWNSCALE_ENABLED;
   1673         }
   1674     }
   1675 
   1676     setMdpFlags(ctx, layer, mdpFlags, downscale, transform);
   1677 
   1678     //if 90 component or downscale, use rot
   1679     if((has90Transform(layer) && isRotationDoable(ctx, hnd)) || downscale) {
   1680         *rot = ctx->mRotMgr->getNext();
   1681         if(*rot == NULL) return -1;
   1682         ctx->mLayerRotMap[dpy]->add(layer, *rot);
   1683         // BWC is not tested for other formats So enable it only for YUV format
   1684         if(!dpy && isYuvBuffer(hnd))
   1685             BwcPM::setBwc(crop, dst, transform, mdpFlags);
   1686         //Configure rotator for pre-rotation
   1687         if(configRotator(*rot, whf, crop, mdpFlags, orient, downscale) < 0) {
   1688             ALOGE("%s: configRotator failed!", __FUNCTION__);
   1689             return -1;
   1690         }
   1691         updateSource(orient, whf, crop, *rot);
   1692         rotFlags |= ovutils::ROT_PREROTATED;
   1693     }
   1694 
   1695     //For the mdp, since either we are pre-rotating or MDP does flips
   1696     orient = OVERLAY_TRANSFORM_0;
   1697     transform = 0;
   1698     PipeArgs parg(mdpFlags, whf, z, isFg,
   1699                   static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
   1700                   (ovutils::eBlending) getBlending(layer->blending));
   1701 
   1702     if(configMdp(ctx->mOverlay, parg, orient, crop, dst, metadata, dest) < 0) {
   1703         ALOGE("%s: commit failed for low res panel", __FUNCTION__);
   1704         return -1;
   1705     }
   1706     return 0;
   1707 }
   1708 
   1709 //Helper to 1) Ensure crops dont have gaps 2) Ensure L and W are even
   1710 void sanitizeSourceCrop(hwc_rect_t& cropL, hwc_rect_t& cropR,
   1711         private_handle_t *hnd) {
   1712     if(cropL.right - cropL.left) {
   1713         if(isYuvBuffer(hnd)) {
   1714             //Always safe to even down left
   1715             ovutils::even_floor(cropL.left);
   1716             //If right is even, automatically width is even, since left is
   1717             //already even
   1718             ovutils::even_floor(cropL.right);
   1719         }
   1720         //Make sure there are no gaps between left and right splits if the layer
   1721         //is spread across BOTH halves
   1722         if(cropR.right - cropR.left) {
   1723             cropR.left = cropL.right;
   1724         }
   1725     }
   1726 
   1727     if(cropR.right - cropR.left) {
   1728         if(isYuvBuffer(hnd)) {
   1729             //Always safe to even down left
   1730             ovutils::even_floor(cropR.left);
   1731             //If right is even, automatically width is even, since left is
   1732             //already even
   1733             ovutils::even_floor(cropR.right);
   1734         }
   1735     }
   1736 }
   1737 
   1738 int configureSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
   1739         const int& dpy, eMdpFlags& mdpFlagsL, eZorder& z,
   1740         eIsFg& isFg, const eDest& lDest, const eDest& rDest,
   1741         Rotator **rot) {
   1742     private_handle_t *hnd = (private_handle_t *)layer->handle;
   1743     if(!hnd) {
   1744         ALOGE("%s: layer handle is NULL", __FUNCTION__);
   1745         return -1;
   1746     }
   1747 
   1748     MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
   1749 
   1750     int hw_w = ctx->dpyAttr[dpy].xres;
   1751     int hw_h = ctx->dpyAttr[dpy].yres;
   1752     hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
   1753     hwc_rect_t dst = layer->displayFrame;
   1754     int transform = layer->transform;
   1755     eTransform orient = static_cast<eTransform>(transform);
   1756     const int downscale = 0;
   1757     int rotFlags = ROT_FLAGS_NONE;
   1758     uint32_t format = ovutils::getMdpFormat(hnd->format, isTileRendered(hnd));
   1759     Whf whf(getWidth(hnd), getHeight(hnd), format, (uint32_t)hnd->size);
   1760 
   1761     // Handle R/B swap
   1762     if (layer->flags & HWC_FORMAT_RB_SWAP) {
   1763         if (hnd->format == HAL_PIXEL_FORMAT_RGBA_8888)
   1764             whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRA_8888);
   1765         else if (hnd->format == HAL_PIXEL_FORMAT_RGBX_8888)
   1766             whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRX_8888);
   1767     }
   1768 
   1769     /* Calculate the external display position based on MDP downscale,
   1770        ActionSafe, and extorientation features. */
   1771     calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient);
   1772 
   1773     setMdpFlags(ctx, layer, mdpFlagsL, 0, transform);
   1774 
   1775     if(lDest != OV_INVALID && rDest != OV_INVALID) {
   1776         //Enable overfetch
   1777         setMdpFlags(mdpFlagsL, OV_MDSS_MDP_DUAL_PIPE);
   1778     }
   1779 
   1780     //Will do something only if feature enabled and conditions suitable
   1781     //hollow call otherwise
   1782     if(ctx->mAD->prepare(ctx, crop, whf, hnd)) {
   1783         overlay::Writeback *wb = overlay::Writeback::getInstance();
   1784         whf.format = wb->getOutputFormat();
   1785     }
   1786 
   1787     if(has90Transform(layer) && isRotationDoable(ctx, hnd)) {
   1788         (*rot) = ctx->mRotMgr->getNext();
   1789         if((*rot) == NULL) return -1;
   1790         ctx->mLayerRotMap[dpy]->add(layer, *rot);
   1791         //Configure rotator for pre-rotation
   1792         if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale) < 0) {
   1793             ALOGE("%s: configRotator failed!", __FUNCTION__);
   1794             return -1;
   1795         }
   1796         updateSource(orient, whf, crop, *rot);
   1797         rotFlags |= ROT_PREROTATED;
   1798     }
   1799 
   1800     eMdpFlags mdpFlagsR = mdpFlagsL;
   1801     setMdpFlags(mdpFlagsR, OV_MDSS_MDP_RIGHT_MIXER);
   1802 
   1803     hwc_rect_t tmp_cropL = {0}, tmp_dstL = {0};
   1804     hwc_rect_t tmp_cropR = {0}, tmp_dstR = {0};
   1805 
   1806     const int lSplit = getLeftSplit(ctx, dpy);
   1807 
   1808     // Calculate Left rects
   1809     if(dst.left < lSplit) {
   1810         tmp_cropL = crop;
   1811         tmp_dstL = dst;
   1812         hwc_rect_t scissor = {0, 0, lSplit, hw_h };
   1813         scissor = getIntersection(ctx->mViewFrame[dpy], scissor);
   1814         qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
   1815     }
   1816 
   1817     // Calculate Right rects
   1818     if(dst.right > lSplit) {
   1819         tmp_cropR = crop;
   1820         tmp_dstR = dst;
   1821         hwc_rect_t scissor = {lSplit, 0, hw_w, hw_h };
   1822         scissor = getIntersection(ctx->mViewFrame[dpy], scissor);
   1823         qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
   1824     }
   1825 
   1826     sanitizeSourceCrop(tmp_cropL, tmp_cropR, hnd);
   1827 
   1828     //When buffer is H-flipped, contents of mixer config also needs to swapped
   1829     //Not needed if the layer is confined to one half of the screen.
   1830     //If rotator has been used then it has also done the flips, so ignore them.
   1831     if((orient & OVERLAY_TRANSFORM_FLIP_H) && (dst.left < lSplit) &&
   1832             (dst.right > lSplit) && (*rot) == NULL) {
   1833         hwc_rect_t new_cropR;
   1834         new_cropR.left = tmp_cropL.left;
   1835         new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
   1836 
   1837         hwc_rect_t new_cropL;
   1838         new_cropL.left  = new_cropR.right;
   1839         new_cropL.right = tmp_cropR.right;
   1840 
   1841         tmp_cropL.left =  new_cropL.left;
   1842         tmp_cropL.right =  new_cropL.right;
   1843 
   1844         tmp_cropR.left = new_cropR.left;
   1845         tmp_cropR.right =  new_cropR.right;
   1846 
   1847     }
   1848 
   1849     //For the mdp, since either we are pre-rotating or MDP does flips
   1850     orient = OVERLAY_TRANSFORM_0;
   1851     transform = 0;
   1852 
   1853     //configure left mixer
   1854     if(lDest != OV_INVALID) {
   1855         PipeArgs pargL(mdpFlagsL, whf, z, isFg,
   1856                        static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
   1857                        (ovutils::eBlending) getBlending(layer->blending));
   1858 
   1859         if(configMdp(ctx->mOverlay, pargL, orient,
   1860                 tmp_cropL, tmp_dstL, metadata, lDest) < 0) {
   1861             ALOGE("%s: commit failed for left mixer config", __FUNCTION__);
   1862             return -1;
   1863         }
   1864     }
   1865 
   1866     //configure right mixer
   1867     if(rDest != OV_INVALID) {
   1868         PipeArgs pargR(mdpFlagsR, whf, z, isFg,
   1869                        static_cast<eRotFlags>(rotFlags),
   1870                        layer->planeAlpha,
   1871                        (ovutils::eBlending) getBlending(layer->blending));
   1872         tmp_dstR.right = tmp_dstR.right - lSplit;
   1873         tmp_dstR.left = tmp_dstR.left - lSplit;
   1874         if(configMdp(ctx->mOverlay, pargR, orient,
   1875                 tmp_cropR, tmp_dstR, metadata, rDest) < 0) {
   1876             ALOGE("%s: commit failed for right mixer config", __FUNCTION__);
   1877             return -1;
   1878         }
   1879     }
   1880 
   1881     return 0;
   1882 }
   1883 
   1884 int configureSourceSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
   1885         const int& dpy, eMdpFlags& mdpFlagsL, eZorder& z,
   1886         eIsFg& isFg, const eDest& lDest, const eDest& rDest,
   1887         Rotator **rot) {
   1888     private_handle_t *hnd = (private_handle_t *)layer->handle;
   1889     if(!hnd) {
   1890         ALOGE("%s: layer handle is NULL", __FUNCTION__);
   1891         return -1;
   1892     }
   1893 
   1894     MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
   1895 
   1896     hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);;
   1897     hwc_rect_t dst = layer->displayFrame;
   1898     int transform = layer->transform;
   1899     eTransform orient = static_cast<eTransform>(transform);
   1900     const int downscale = 0;
   1901     int rotFlags = ROT_FLAGS_NONE;
   1902     //Splitting only YUV layer on primary panel needs different zorders
   1903     //for both layers as both the layers are configured to single mixer
   1904     eZorder lz = z;
   1905     eZorder rz = (eZorder)(z + 1);
   1906 
   1907     Whf whf(getWidth(hnd), getHeight(hnd),
   1908             getMdpFormat(hnd->format), (uint32_t)hnd->size);
   1909 
   1910     /* Calculate the external display position based on MDP downscale,
   1911        ActionSafe, and extorientation features. */
   1912     calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient);
   1913 
   1914     setMdpFlags(ctx, layer, mdpFlagsL, 0, transform);
   1915     trimLayer(ctx, dpy, transform, crop, dst);
   1916 
   1917     if(has90Transform(layer) && isRotationDoable(ctx, hnd)) {
   1918         (*rot) = ctx->mRotMgr->getNext();
   1919         if((*rot) == NULL) return -1;
   1920         ctx->mLayerRotMap[dpy]->add(layer, *rot);
   1921         // BWC is not tested for other formats So enable it only for YUV format
   1922         if(!dpy && isYuvBuffer(hnd))
   1923             BwcPM::setBwc(crop, dst, transform, mdpFlagsL);
   1924         //Configure rotator for pre-rotation
   1925         if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale) < 0) {
   1926             ALOGE("%s: configRotator failed!", __FUNCTION__);
   1927             return -1;
   1928         }
   1929         updateSource(orient, whf, crop, *rot);
   1930         rotFlags |= ROT_PREROTATED;
   1931     }
   1932 
   1933     eMdpFlags mdpFlagsR = mdpFlagsL;
   1934     int lSplit = dst.left + (dst.right - dst.left)/2;
   1935 
   1936     hwc_rect_t tmp_cropL = {0}, tmp_dstL = {0};
   1937     hwc_rect_t tmp_cropR = {0}, tmp_dstR = {0};
   1938 
   1939     if(lDest != OV_INVALID) {
   1940         tmp_cropL = crop;
   1941         tmp_dstL = dst;
   1942         hwc_rect_t scissor = {dst.left, dst.top, lSplit, dst.bottom };
   1943         qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
   1944     }
   1945     if(rDest != OV_INVALID) {
   1946         tmp_cropR = crop;
   1947         tmp_dstR = dst;
   1948         hwc_rect_t scissor = {lSplit, dst.top, dst.right, dst.bottom };
   1949         qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
   1950     }
   1951 
   1952     sanitizeSourceCrop(tmp_cropL, tmp_cropR, hnd);
   1953 
   1954     //When buffer is H-flipped, contents of mixer config also needs to swapped
   1955     //Not needed if the layer is confined to one half of the screen.
   1956     //If rotator has been used then it has also done the flips, so ignore them.
   1957     if((orient & OVERLAY_TRANSFORM_FLIP_H) && lDest != OV_INVALID
   1958             && rDest != OV_INVALID && (*rot) == NULL) {
   1959         hwc_rect_t new_cropR;
   1960         new_cropR.left = tmp_cropL.left;
   1961         new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
   1962 
   1963         hwc_rect_t new_cropL;
   1964         new_cropL.left  = new_cropR.right;
   1965         new_cropL.right = tmp_cropR.right;
   1966 
   1967         tmp_cropL.left =  new_cropL.left;
   1968         tmp_cropL.right =  new_cropL.right;
   1969 
   1970         tmp_cropR.left = new_cropR.left;
   1971         tmp_cropR.right =  new_cropR.right;
   1972 
   1973     }
   1974 
   1975     //For the mdp, since either we are pre-rotating or MDP does flips
   1976     orient = OVERLAY_TRANSFORM_0;
   1977     transform = 0;
   1978 
   1979     //configure left half
   1980     if(lDest != OV_INVALID) {
   1981         PipeArgs pargL(mdpFlagsL, whf, lz, isFg,
   1982                 static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
   1983                 (ovutils::eBlending) getBlending(layer->blending));
   1984 
   1985         if(configMdp(ctx->mOverlay, pargL, orient,
   1986                     tmp_cropL, tmp_dstL, metadata, lDest) < 0) {
   1987             ALOGE("%s: commit failed for left half config", __FUNCTION__);
   1988             return -1;
   1989         }
   1990     }
   1991 
   1992     //configure right half
   1993     if(rDest != OV_INVALID) {
   1994         PipeArgs pargR(mdpFlagsR, whf, rz, isFg,
   1995                 static_cast<eRotFlags>(rotFlags),
   1996                 layer->planeAlpha,
   1997                 (ovutils::eBlending) getBlending(layer->blending));
   1998         if(configMdp(ctx->mOverlay, pargR, orient,
   1999                     tmp_cropR, tmp_dstR, metadata, rDest) < 0) {
   2000             ALOGE("%s: commit failed for right half config", __FUNCTION__);
   2001             return -1;
   2002         }
   2003     }
   2004 
   2005     return 0;
   2006 }
   2007 
   2008 bool canUseRotator(hwc_context_t *ctx, int dpy) {
   2009     if(ctx->mOverlay->isDMAMultiplexingSupported() &&
   2010             isSecondaryConnected(ctx) &&
   2011             !ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].isPause) {
   2012         /* mdss driver on certain targets support multiplexing of DMA pipe
   2013          * in LINE and BLOCK modes for writeback panels.
   2014          */
   2015         if(dpy == HWC_DISPLAY_PRIMARY)
   2016             return false;
   2017     }
   2018     if(ctx->mMDP.version == qdutils::MDP_V3_0_4)
   2019         return false;
   2020     return true;
   2021 }
   2022 
   2023 int getLeftSplit(hwc_context_t *ctx, const int& dpy) {
   2024     //Default even split for all displays with high res
   2025     int lSplit = ctx->dpyAttr[dpy].xres / 2;
   2026     if(dpy == HWC_DISPLAY_PRIMARY &&
   2027             qdutils::MDPVersion::getInstance().getLeftSplit()) {
   2028         //Override if split published by driver for primary
   2029         lSplit = qdutils::MDPVersion::getInstance().getLeftSplit();
   2030     }
   2031     return lSplit;
   2032 }
   2033 
   2034 bool isDisplaySplit(hwc_context_t* ctx, int dpy) {
   2035     if(ctx->dpyAttr[dpy].xres > qdutils::MAX_DISPLAY_DIM) {
   2036         return true;
   2037     }
   2038     //For testing we could split primary via device tree values
   2039     if(dpy == HWC_DISPLAY_PRIMARY &&
   2040         qdutils::MDPVersion::getInstance().getRightSplit()) {
   2041         return true;
   2042     }
   2043     return false;
   2044 }
   2045 
   2046 //clear prev layer prop flags and realloc for current frame
   2047 void reset_layer_prop(hwc_context_t* ctx, int dpy, int numAppLayers) {
   2048     if(ctx->layerProp[dpy]) {
   2049        delete[] ctx->layerProp[dpy];
   2050        ctx->layerProp[dpy] = NULL;
   2051     }
   2052     ctx->layerProp[dpy] = new LayerProp[numAppLayers];
   2053 }
   2054 
   2055 bool isAbcInUse(hwc_context_t *ctx){
   2056   return (ctx->enableABC && ctx->listStats[0].renderBufIndexforABC == 0);
   2057 }
   2058 
   2059 void dumpBuffer(private_handle_t *ohnd, char *bufferName) {
   2060     if (ohnd != NULL && ohnd->base) {
   2061         char dumpFilename[PATH_MAX];
   2062         bool bResult = false;
   2063         snprintf(dumpFilename, sizeof(dumpFilename), "/data/%s.%s.%dx%d.raw",
   2064             bufferName,
   2065             overlay::utils::getFormatString(utils::getMdpFormat(ohnd->format)),
   2066             getWidth(ohnd), getHeight(ohnd));
   2067         FILE* fp = fopen(dumpFilename, "w+");
   2068         if (NULL != fp) {
   2069             bResult = (bool) fwrite((void*)ohnd->base, ohnd->size, 1, fp);
   2070             fclose(fp);
   2071         }
   2072         ALOGD("Buffer[%s] Dump to %s: %s",
   2073         bufferName, dumpFilename, bResult ? "Success" : "Fail");
   2074     }
   2075 }
   2076 
   2077 bool isGLESComp(hwc_context_t *ctx,
   2078                      hwc_display_contents_1_t* list) {
   2079     int numAppLayers = ctx->listStats[HWC_DISPLAY_PRIMARY].numAppLayers;
   2080     for(int index = 0; index < numAppLayers; index++) {
   2081         hwc_layer_1_t* layer = &(list->hwLayers[index]);
   2082         if(layer->compositionType == HWC_FRAMEBUFFER)
   2083             return true;
   2084     }
   2085     return false;
   2086 }
   2087 
   2088 void setGPUHint(hwc_context_t* ctx, hwc_display_contents_1_t* list) {
   2089     struct gpu_hint_info *gpuHint = &ctx->mGPUHintInfo;
   2090     if(!gpuHint->mGpuPerfModeEnable || !ctx || !list)
   2091         return;
   2092 
   2093 #ifdef QCOM_BSP
   2094     /* Set the GPU hint flag to high for MIXED/GPU composition only for
   2095        first frame after MDP -> GPU/MIXED mode transition. Set the GPU
   2096        hint to default if the previous composition is GPU or current GPU
   2097        composition is due to idle fallback */
   2098     if(!gpuHint->mEGLDisplay || !gpuHint->mEGLContext) {
   2099         gpuHint->mEGLDisplay = eglGetCurrentDisplay();
   2100         if(!gpuHint->mEGLDisplay) {
   2101             ALOGW("%s Warning: EGL current display is NULL", __FUNCTION__);
   2102             return;
   2103         }
   2104         gpuHint->mEGLContext = eglGetCurrentContext();
   2105         if(!gpuHint->mEGLContext) {
   2106             ALOGW("%s Warning: EGL current context is NULL", __FUNCTION__);
   2107             return;
   2108         }
   2109     }
   2110     if(isGLESComp(ctx, list)) {
   2111         if(gpuHint->mCompositionState != COMPOSITION_STATE_GPU
   2112             && !MDPComp::isIdleFallback()) {
   2113             EGLint attr_list[] = {EGL_GPU_HINT_1,
   2114                                   EGL_GPU_LEVEL_3,
   2115                                   EGL_NONE };
   2116             if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_3) &&
   2117                 !eglGpuPerfHintQCOM(gpuHint->mEGLDisplay,
   2118                                     gpuHint->mEGLContext, attr_list)) {
   2119                 ALOGW("eglGpuPerfHintQCOM failed for Built in display");
   2120             } else {
   2121                 gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_3;
   2122                 gpuHint->mCompositionState = COMPOSITION_STATE_GPU;
   2123             }
   2124         } else {
   2125             EGLint attr_list[] = {EGL_GPU_HINT_1,
   2126                                   EGL_GPU_LEVEL_0,
   2127                                   EGL_NONE };
   2128             if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_0) &&
   2129                 !eglGpuPerfHintQCOM(gpuHint->mEGLDisplay,
   2130                                     gpuHint->mEGLContext, attr_list)) {
   2131                 ALOGW("eglGpuPerfHintQCOM failed for Built in display");
   2132             } else {
   2133                 gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_0;
   2134             }
   2135             if(MDPComp::isIdleFallback()) {
   2136                 gpuHint->mCompositionState = COMPOSITION_STATE_IDLE_FALLBACK;
   2137             }
   2138         }
   2139     } else {
   2140         /* set the GPU hint flag to default for MDP composition */
   2141         EGLint attr_list[] = {EGL_GPU_HINT_1,
   2142                               EGL_GPU_LEVEL_0,
   2143                               EGL_NONE };
   2144         if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_0) &&
   2145                 !eglGpuPerfHintQCOM(gpuHint->mEGLDisplay,
   2146                                     gpuHint->mEGLContext, attr_list)) {
   2147             ALOGW("eglGpuPerfHintQCOM failed for Built in display");
   2148         } else {
   2149             gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_0;
   2150         }
   2151         gpuHint->mCompositionState = COMPOSITION_STATE_MDP;
   2152     }
   2153 #endif
   2154 }
   2155 
   2156 bool isPeripheral(const hwc_rect_t& rect1, const hwc_rect_t& rect2) {
   2157     // To be peripheral, 3 boundaries should match.
   2158     uint8_t eqBounds = 0;
   2159     if (rect1.left == rect2.left)
   2160         eqBounds++;
   2161     if (rect1.top == rect2.top)
   2162         eqBounds++;
   2163     if (rect1.right == rect2.right)
   2164         eqBounds++;
   2165     if (rect1.bottom == rect2.bottom)
   2166         eqBounds++;
   2167     return (eqBounds == 3);
   2168 }
   2169 
   2170 void BwcPM::setBwc(const hwc_rect_t& crop,
   2171             const hwc_rect_t& dst, const int& transform,
   2172             ovutils::eMdpFlags& mdpFlags) {
   2173     //Target doesnt support Bwc
   2174     if(!qdutils::MDPVersion::getInstance().supportsBWC()) {
   2175         return;
   2176     }
   2177     int src_w = crop.right - crop.left;
   2178     int src_h = crop.bottom - crop.top;
   2179     int dst_w = dst.right - dst.left;
   2180     int dst_h = dst.bottom - dst.top;
   2181     if(transform & HAL_TRANSFORM_ROT_90) {
   2182         swap(src_w, src_h);
   2183     }
   2184     //src width > MAX mixer supported dim
   2185     if(src_w > qdutils::MAX_DISPLAY_DIM) {
   2186         return;
   2187     }
   2188     //Decimation necessary, cannot use BWC. H/W requirement.
   2189     if(qdutils::MDPVersion::getInstance().supportsDecimation()) {
   2190         uint8_t horzDeci = 0;
   2191         uint8_t vertDeci = 0;
   2192         ovutils::getDecimationFactor(src_w, src_h, dst_w, dst_h, horzDeci,
   2193                 vertDeci);
   2194         if(horzDeci || vertDeci) return;
   2195     }
   2196     //Property
   2197     char value[PROPERTY_VALUE_MAX];
   2198     property_get("debug.disable.bwc", value, "0");
   2199      if(atoi(value)) return;
   2200 
   2201     ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDSS_MDP_BWC_EN);
   2202 }
   2203 
   2204 void LayerRotMap::add(hwc_layer_1_t* layer, Rotator *rot) {
   2205     if(mCount >= MAX_SESS) return;
   2206     mLayer[mCount] = layer;
   2207     mRot[mCount] = rot;
   2208     mCount++;
   2209 }
   2210 
   2211 void LayerRotMap::reset() {
   2212     for (int i = 0; i < MAX_SESS; i++) {
   2213         mLayer[i] = 0;
   2214         mRot[i] = 0;
   2215     }
   2216     mCount = 0;
   2217 }
   2218 
   2219 void LayerRotMap::clear() {
   2220     RotMgr::getInstance()->markUnusedTop(mCount);
   2221     reset();
   2222 }
   2223 
   2224 void LayerRotMap::setReleaseFd(const int& fence) {
   2225     for(uint32_t i = 0; i < mCount; i++) {
   2226         mRot[i]->setReleaseFd(dup(fence));
   2227     }
   2228 }
   2229 
   2230 void resetROI(hwc_context_t *ctx, const int dpy) {
   2231     const int fbXRes = (int)ctx->dpyAttr[dpy].xres;
   2232     const int fbYRes = (int)ctx->dpyAttr[dpy].yres;
   2233     if(isDisplaySplit(ctx, dpy)) {
   2234         const int lSplit = getLeftSplit(ctx, dpy);
   2235         ctx->listStats[dpy].lRoi = (struct hwc_rect){0, 0, lSplit, fbYRes};
   2236         ctx->listStats[dpy].rRoi = (struct hwc_rect){lSplit, 0, fbXRes, fbYRes};
   2237     } else  {
   2238         ctx->listStats[dpy].lRoi = (struct hwc_rect){0, 0,fbXRes, fbYRes};
   2239         ctx->listStats[dpy].rRoi = (struct hwc_rect){0, 0, 0, 0};
   2240     }
   2241 }
   2242 
   2243 hwc_rect_t getSanitizeROI(struct hwc_rect roi, hwc_rect boundary)
   2244 {
   2245    if(!isValidRect(roi))
   2246       return roi;
   2247 
   2248    struct hwc_rect t_roi = roi;
   2249 
   2250    const int LEFT_ALIGN = qdutils::MDPVersion::getInstance().getLeftAlign();
   2251    const int WIDTH_ALIGN = qdutils::MDPVersion::getInstance().getWidthAlign();
   2252    const int TOP_ALIGN = qdutils::MDPVersion::getInstance().getTopAlign();
   2253    const int HEIGHT_ALIGN = qdutils::MDPVersion::getInstance().getHeightAlign();
   2254    const int MIN_WIDTH = qdutils::MDPVersion::getInstance().getMinROIWidth();
   2255    const int MIN_HEIGHT = qdutils::MDPVersion::getInstance().getMinROIHeight();
   2256 
   2257    /* Align to minimum width recommended by the panel */
   2258    if((t_roi.right - t_roi.left) < MIN_WIDTH) {
   2259        if((t_roi.left + MIN_WIDTH) > boundary.right)
   2260            t_roi.left = t_roi.right - MIN_WIDTH;
   2261        else
   2262            t_roi.right = t_roi.left + MIN_WIDTH;
   2263    }
   2264 
   2265   /* Align to minimum height recommended by the panel */
   2266    if((t_roi.bottom - t_roi.top) < MIN_HEIGHT) {
   2267        if((t_roi.top + MIN_HEIGHT) > boundary.bottom)
   2268            t_roi.top = t_roi.bottom - MIN_HEIGHT;
   2269        else
   2270            t_roi.bottom = t_roi.top + MIN_HEIGHT;
   2271    }
   2272 
   2273    /* Align left and width to meet panel restrictions */
   2274    if(LEFT_ALIGN)
   2275        t_roi.left = t_roi.left - (t_roi.left % LEFT_ALIGN);
   2276 
   2277    if(WIDTH_ALIGN) {
   2278        int width = t_roi.right - t_roi.left;
   2279        width = WIDTH_ALIGN * ((width + (WIDTH_ALIGN - 1)) / WIDTH_ALIGN);
   2280        t_roi.right = t_roi.left + width;
   2281 
   2282        if(t_roi.right > boundary.right) {
   2283            t_roi.right = boundary.right;
   2284            t_roi.left = t_roi.right - width;
   2285 
   2286            if(LEFT_ALIGN)
   2287                t_roi.left = t_roi.left - (t_roi.left % LEFT_ALIGN);
   2288        }
   2289    }
   2290 
   2291 
   2292    /* Align top and height to meet panel restrictions */
   2293    if(TOP_ALIGN)
   2294        t_roi.top = t_roi.top - (t_roi.top % TOP_ALIGN);
   2295 
   2296    if(HEIGHT_ALIGN) {
   2297        int height = t_roi.bottom - t_roi.top;
   2298        height = HEIGHT_ALIGN *  ((height + (HEIGHT_ALIGN - 1)) / HEIGHT_ALIGN);
   2299        t_roi.bottom = t_roi.top  + height;
   2300 
   2301        if(t_roi.bottom > boundary.bottom) {
   2302            t_roi.bottom = boundary.bottom;
   2303            t_roi.top = t_roi.bottom - height;
   2304 
   2305            if(TOP_ALIGN)
   2306                t_roi.top = t_roi.top - (t_roi.top % TOP_ALIGN);
   2307        }
   2308    }
   2309 
   2310 
   2311    return t_roi;
   2312 }
   2313 
   2314 };//namespace qhwc
   2315