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 #ifdef DEBUG_SWAPINTERVAL
   1291     char property[PROPERTY_VALUE_MAX];
   1292     if(property_get("debug.egl.swapinterval", property, "1") > 0) {
   1293         if(atoi(property) == 0)
   1294             swapzero = true;
   1295     }
   1296 #endif
   1297 
   1298     bool isExtAnimating = false;
   1299     if(dpy)
   1300        isExtAnimating = ctx->listStats[dpy].isDisplayAnimating;
   1301 
   1302     //Send acquireFenceFds to rotator
   1303     for(uint32_t i = 0; i < ctx->mLayerRotMap[dpy]->getCount(); i++) {
   1304         int rotFd = ctx->mRotMgr->getRotDevFd();
   1305         int rotReleaseFd = -1;
   1306         overlay::Rotator* currRot = ctx->mLayerRotMap[dpy]->getRot(i);
   1307         hwc_layer_1_t* currLayer = ctx->mLayerRotMap[dpy]->getLayer(i);
   1308         if((currRot == NULL) || (currLayer == NULL)) {
   1309             continue;
   1310         }
   1311         struct mdp_buf_sync rotData;
   1312         memset(&rotData, 0, sizeof(rotData));
   1313         rotData.acq_fen_fd =
   1314                 &currLayer->acquireFenceFd;
   1315         rotData.rel_fen_fd = &rotReleaseFd; //driver to populate this
   1316         rotData.session_id = currRot->getSessId();
   1317         if(currLayer->acquireFenceFd >= 0) {
   1318             rotData.acq_fen_fd_cnt = 1; //1 ioctl call per rot session
   1319         }
   1320         int ret = 0;
   1321         ret = ioctl(rotFd, MSMFB_BUFFER_SYNC, &rotData);
   1322         if(ret < 0) {
   1323             ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed for rot sync, err=%s",
   1324                     __FUNCTION__, strerror(errno));
   1325             close(rotReleaseFd);
   1326         } else {
   1327             close(currLayer->acquireFenceFd);
   1328             //For MDP to wait on.
   1329             currLayer->acquireFenceFd =
   1330                     dup(rotReleaseFd);
   1331             //A buffer is free to be used by producer as soon as its copied to
   1332             //rotator
   1333             currLayer->releaseFenceFd =
   1334                     rotReleaseFd;
   1335         }
   1336     }
   1337 
   1338     //Accumulate acquireFenceFds for MDP Overlays
   1339     if(list->outbufAcquireFenceFd >= 0) {
   1340         //Writeback output buffer
   1341         acquireFd[count++] = list->outbufAcquireFenceFd;
   1342     }
   1343 
   1344     for(uint32_t i = 0; i < list->numHwLayers; i++) {
   1345         if(((isAbcInUse(ctx)== true ) ||
   1346           (list->hwLayers[i].compositionType == HWC_OVERLAY)) &&
   1347                         list->hwLayers[i].acquireFenceFd >= 0) {
   1348             if(UNLIKELY(swapzero))
   1349                 acquireFd[count++] = -1;
   1350             // if ABC is enabled for more than one layer.
   1351             // renderBufIndexforABC will work as FB.Hence
   1352             // set the acquireFD from fd - which is coming from copybit
   1353             else if(fd >= 0 && (isAbcInUse(ctx) == true)) {
   1354                 if(ctx->listStats[dpy].renderBufIndexforABC ==(int32_t)i)
   1355                    acquireFd[count++] = fd;
   1356                 else
   1357                    continue;
   1358             } else
   1359                 acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
   1360         }
   1361         if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
   1362             if(UNLIKELY(swapzero))
   1363                 acquireFd[count++] = -1;
   1364             else if(fd >= 0) {
   1365                 //set the acquireFD from fd - which is coming from c2d
   1366                 acquireFd[count++] = fd;
   1367                 // Buffer sync IOCTL should be async when using c2d fence is
   1368                 // used
   1369                 data.flags &= ~MDP_BUF_SYNC_FLAG_WAIT;
   1370             } else if(list->hwLayers[i].acquireFenceFd >= 0)
   1371                 acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
   1372         }
   1373     }
   1374 
   1375     if ((fd >= 0) && !dpy && ctx->mPtorInfo.isActive()) {
   1376         // Acquire c2d fence of Overlap render buffer
   1377         acquireFd[count++] = fd;
   1378     }
   1379 
   1380     data.acq_fen_fd_cnt = count;
   1381     fbFd = ctx->dpyAttr[dpy].fd;
   1382 
   1383     //Waits for acquire fences, returns a release fence
   1384     if(LIKELY(!swapzero)) {
   1385         ret = ioctl(fbFd, MSMFB_BUFFER_SYNC, &data);
   1386     }
   1387 
   1388     if(ret < 0) {
   1389         ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed, err=%s",
   1390                   __FUNCTION__, strerror(errno));
   1391         ALOGE("%s: acq_fen_fd_cnt=%d flags=%d fd=%d dpy=%d numHwLayers=%zu",
   1392               __FUNCTION__, data.acq_fen_fd_cnt, data.flags, fbFd,
   1393               dpy, list->numHwLayers);
   1394         close(releaseFd);
   1395         releaseFd = -1;
   1396         close(retireFd);
   1397         retireFd = -1;
   1398     }
   1399 
   1400     for(uint32_t i = 0; i < list->numHwLayers; i++) {
   1401         if(list->hwLayers[i].compositionType == HWC_OVERLAY ||
   1402 #ifdef QCOM_BSP
   1403            list->hwLayers[i].compositionType == HWC_BLIT ||
   1404 #endif
   1405            list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
   1406             //Populate releaseFenceFds.
   1407             if(UNLIKELY(swapzero)) {
   1408                 list->hwLayers[i].releaseFenceFd = -1;
   1409             } else if(isExtAnimating) {
   1410                 // Release all the app layer fds immediately,
   1411                 // if animation is in progress.
   1412                 list->hwLayers[i].releaseFenceFd = -1;
   1413             } else if(list->hwLayers[i].releaseFenceFd < 0 ) {
   1414 #ifdef QCOM_BSP
   1415                 //If rotator has not already populated this field
   1416                 // & if it's a not VPU layer
   1417 
   1418                 // if ABC is enabled for more than one layer
   1419                 if(fd >= 0 && (isAbcInUse(ctx) == true) &&
   1420                   ctx->listStats[dpy].renderBufIndexforABC !=(int32_t)i){
   1421                     list->hwLayers[i].releaseFenceFd = dup(fd);
   1422                 } else if((list->hwLayers[i].compositionType == HWC_BLIT)&&
   1423                                                (isAbcInUse(ctx) == false)){
   1424                     //For Blit, the app layers should be released when the Blit
   1425                     //is complete. This fd was passed from copybit->draw
   1426                     list->hwLayers[i].releaseFenceFd = dup(fd);
   1427                 } else
   1428 #endif
   1429                 {
   1430                     list->hwLayers[i].releaseFenceFd = dup(releaseFd);
   1431                 }
   1432             }
   1433         }
   1434     }
   1435 
   1436     if(fd >= 0) {
   1437         close(fd);
   1438         fd = -1;
   1439     }
   1440 
   1441     if (!dpy && ctx->mCopyBit[dpy]) {
   1442         if (ctx->mPtorInfo.isActive())
   1443             ctx->mCopyBit[dpy]->setReleaseFdSync(releaseFd);
   1444         else
   1445             ctx->mCopyBit[dpy]->setReleaseFd(releaseFd);
   1446     }
   1447 
   1448     //Signals when MDP finishes reading rotator buffers.
   1449     ctx->mLayerRotMap[dpy]->setReleaseFd(releaseFd);
   1450     close(releaseFd);
   1451     releaseFd = -1;
   1452 
   1453     if(UNLIKELY(swapzero)) {
   1454         list->retireFenceFd = -1;
   1455     } else {
   1456         list->retireFenceFd = retireFd;
   1457     }
   1458     return ret;
   1459 }
   1460 
   1461 void setMdpFlags(hwc_context_t *ctx, hwc_layer_1_t *layer,
   1462         ovutils::eMdpFlags &mdpFlags,
   1463         int rotDownscale, int transform) {
   1464     private_handle_t *hnd = (private_handle_t *)layer->handle;
   1465     MetaData_t *metadata = hnd ? (MetaData_t *)hnd->base_metadata : NULL;
   1466 
   1467     if(layer->blending == HWC_BLENDING_PREMULT) {
   1468         ovutils::setMdpFlags(mdpFlags,
   1469                 ovutils::OV_MDP_BLEND_FG_PREMULT);
   1470     }
   1471 
   1472     if(isYuvBuffer(hnd)) {
   1473         if(isSecureBuffer(hnd)) {
   1474             ovutils::setMdpFlags(mdpFlags,
   1475                     ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
   1476         }
   1477         if(metadata && (metadata->operation & PP_PARAM_INTERLACED) &&
   1478                 metadata->interlaced) {
   1479             ovutils::setMdpFlags(mdpFlags,
   1480                     ovutils::OV_MDP_DEINTERLACE);
   1481         }
   1482     }
   1483 
   1484     if(isSecureDisplayBuffer(hnd)) {
   1485         // Secure display needs both SECURE_OVERLAY and SECURE_DISPLAY_OV
   1486         ovutils::setMdpFlags(mdpFlags,
   1487                              ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
   1488         ovutils::setMdpFlags(mdpFlags,
   1489                              ovutils::OV_MDP_SECURE_DISPLAY_OVERLAY_SESSION);
   1490     }
   1491 
   1492     //Pre-rotation will be used using rotator.
   1493     if(has90Transform(layer) && isRotationDoable(ctx, hnd)) {
   1494         ovutils::setMdpFlags(mdpFlags,
   1495                 ovutils::OV_MDP_SOURCE_ROTATED_90);
   1496     }
   1497     //No 90 component and no rot-downscale then flips done by MDP
   1498     //If we use rot then it might as well do flips
   1499     if(!(transform & HWC_TRANSFORM_ROT_90) && !rotDownscale) {
   1500         if(transform & HWC_TRANSFORM_FLIP_H) {
   1501             ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_FLIP_H);
   1502         }
   1503 
   1504         if(transform & HWC_TRANSFORM_FLIP_V) {
   1505             ovutils::setMdpFlags(mdpFlags,  ovutils::OV_MDP_FLIP_V);
   1506         }
   1507     }
   1508 
   1509     if(metadata &&
   1510         ((metadata->operation & PP_PARAM_HSIC)
   1511         || (metadata->operation & PP_PARAM_IGC)
   1512         || (metadata->operation & PP_PARAM_SHARP2))) {
   1513         ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_PP_EN);
   1514     }
   1515 }
   1516 
   1517 int configRotator(Rotator *rot, Whf& whf,
   1518         hwc_rect_t& crop, const eMdpFlags& mdpFlags,
   1519         const eTransform& orient, const int& downscale) {
   1520 
   1521     // Fix alignments for TILED format
   1522     if(whf.format == MDP_Y_CRCB_H2V2_TILE ||
   1523                             whf.format == MDP_Y_CBCR_H2V2_TILE) {
   1524         whf.w =  utils::alignup(whf.w, 64);
   1525         whf.h = utils::alignup(whf.h, 32);
   1526     }
   1527     rot->setSource(whf);
   1528 
   1529     if (qdutils::MDPVersion::getInstance().getMDPVersion() >=
   1530         qdutils::MDSS_V5) {
   1531          Dim rotCrop(crop.left, crop.top, crop.right - crop.left,
   1532                 crop.bottom - crop.top);
   1533         rot->setCrop(rotCrop);
   1534     }
   1535 
   1536     rot->setFlags(mdpFlags);
   1537     rot->setTransform(orient);
   1538     rot->setDownscale(downscale);
   1539     if(!rot->commit()) return -1;
   1540     return 0;
   1541 }
   1542 
   1543 int configMdp(Overlay *ov, const PipeArgs& parg,
   1544         const eTransform& orient, const hwc_rect_t& crop,
   1545         const hwc_rect_t& pos, const MetaData_t *metadata,
   1546         const eDest& dest) {
   1547     ov->setSource(parg, dest);
   1548     ov->setTransform(orient, dest);
   1549 
   1550     int crop_w = crop.right - crop.left;
   1551     int crop_h = crop.bottom - crop.top;
   1552     Dim dcrop(crop.left, crop.top, crop_w, crop_h);
   1553     ov->setCrop(dcrop, dest);
   1554 
   1555     int posW = pos.right - pos.left;
   1556     int posH = pos.bottom - pos.top;
   1557     Dim position(pos.left, pos.top, posW, posH);
   1558     ov->setPosition(position, dest);
   1559 
   1560     if (metadata)
   1561         ov->setVisualParams(*metadata, dest);
   1562 
   1563     if (!ov->commit(dest)) {
   1564         return -1;
   1565     }
   1566     return 0;
   1567 }
   1568 
   1569 int configColorLayer(hwc_context_t *ctx, hwc_layer_1_t *layer,
   1570         const int& dpy, eMdpFlags& mdpFlags, eZorder& z,
   1571         eIsFg& isFg, const eDest& dest) {
   1572 
   1573     hwc_rect_t dst = layer->displayFrame;
   1574     trimLayer(ctx, dpy, 0, dst, dst);
   1575 
   1576     int w = ctx->dpyAttr[dpy].xres;
   1577     int h = ctx->dpyAttr[dpy].yres;
   1578     int dst_w = dst.right - dst.left;
   1579     int dst_h = dst.bottom - dst.top;
   1580     uint32_t color = layer->transform;
   1581     Whf whf(w, h, getMdpFormat(HAL_PIXEL_FORMAT_RGBA_8888), 0);
   1582 
   1583     ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_SOLID_FILL);
   1584     if (layer->blending == HWC_BLENDING_PREMULT)
   1585         ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_BLEND_FG_PREMULT);
   1586 
   1587     PipeArgs parg(mdpFlags, whf, z, isFg, static_cast<eRotFlags>(0),
   1588                   layer->planeAlpha,
   1589                   (ovutils::eBlending) getBlending(layer->blending));
   1590 
   1591     // Configure MDP pipe for Color layer
   1592     Dim pos(dst.left, dst.top, dst_w, dst_h);
   1593     ctx->mOverlay->setSource(parg, dest);
   1594     ctx->mOverlay->setColor(color, dest);
   1595     ctx->mOverlay->setTransform(0, dest);
   1596     ctx->mOverlay->setCrop(pos, dest);
   1597     ctx->mOverlay->setPosition(pos, dest);
   1598 
   1599     if (!ctx->mOverlay->commit(dest)) {
   1600         ALOGE("%s: Configure color layer failed!", __FUNCTION__);
   1601         return -1;
   1602     }
   1603     return 0;
   1604 }
   1605 
   1606 void updateSource(eTransform& orient, Whf& whf,
   1607         hwc_rect_t& crop, Rotator *rot) {
   1608     Dim transformedCrop(crop.left, crop.top,
   1609             crop.right - crop.left,
   1610             crop.bottom - crop.top);
   1611     if (qdutils::MDPVersion::getInstance().getMDPVersion() >=
   1612         qdutils::MDSS_V5) {
   1613         //B-family rotator internally could modify destination dimensions if
   1614         //downscaling is supported
   1615         whf = rot->getDstWhf();
   1616         transformedCrop = rot->getDstDimensions();
   1617     } else {
   1618         //A-family rotator rotates entire buffer irrespective of crop, forcing
   1619         //us to recompute the crop based on transform
   1620         orient = static_cast<eTransform>(ovutils::getMdpOrient(orient));
   1621         preRotateSource(orient, whf, transformedCrop);
   1622     }
   1623 
   1624     crop.left = transformedCrop.x;
   1625     crop.top = transformedCrop.y;
   1626     crop.right = transformedCrop.x + transformedCrop.w;
   1627     crop.bottom = transformedCrop.y + transformedCrop.h;
   1628 }
   1629 
   1630 int configureNonSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
   1631         const int& dpy, eMdpFlags& mdpFlags, eZorder& z,
   1632         eIsFg& isFg, const eDest& dest, Rotator **rot) {
   1633 
   1634     private_handle_t *hnd = (private_handle_t *)layer->handle;
   1635 
   1636     if(!hnd) {
   1637         if (layer->flags & HWC_COLOR_FILL) {
   1638             // Configure Color layer
   1639             return configColorLayer(ctx, layer, dpy, mdpFlags, z, isFg, dest);
   1640         }
   1641         ALOGE("%s: layer handle is NULL", __FUNCTION__);
   1642         return -1;
   1643     }
   1644 
   1645     MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
   1646 
   1647     hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
   1648     hwc_rect_t dst = layer->displayFrame;
   1649     int transform = layer->transform;
   1650     eTransform orient = static_cast<eTransform>(transform);
   1651     int downscale = 0;
   1652     int rotFlags = ovutils::ROT_FLAGS_NONE;
   1653     uint32_t format = ovutils::getMdpFormat(hnd->format, isTileRendered(hnd));
   1654     Whf whf(getWidth(hnd), getHeight(hnd), format, (uint32_t)hnd->size);
   1655 
   1656     // Handle R/B swap
   1657     if (layer->flags & HWC_FORMAT_RB_SWAP) {
   1658         if (hnd->format == HAL_PIXEL_FORMAT_RGBA_8888)
   1659             whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRA_8888);
   1660         else if (hnd->format == HAL_PIXEL_FORMAT_RGBX_8888)
   1661             whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRX_8888);
   1662     }
   1663 
   1664     calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient);
   1665 
   1666     if(isYuvBuffer(hnd) && ctx->mMDP.version >= qdutils::MDP_V4_2 &&
   1667        ctx->mMDP.version < qdutils::MDSS_V5) {
   1668         downscale =  getDownscaleFactor(
   1669             crop.right - crop.left,
   1670             crop.bottom - crop.top,
   1671             dst.right - dst.left,
   1672             dst.bottom - dst.top);
   1673         if(downscale) {
   1674             rotFlags = ROT_DOWNSCALE_ENABLED;
   1675         }
   1676     }
   1677 
   1678     setMdpFlags(ctx, layer, mdpFlags, downscale, transform);
   1679 
   1680     //if 90 component or downscale, use rot
   1681     if((has90Transform(layer) && isRotationDoable(ctx, hnd)) || downscale) {
   1682         *rot = ctx->mRotMgr->getNext();
   1683         if(*rot == NULL) return -1;
   1684         ctx->mLayerRotMap[dpy]->add(layer, *rot);
   1685         // BWC is not tested for other formats So enable it only for YUV format
   1686         if(!dpy && isYuvBuffer(hnd))
   1687             BwcPM::setBwc(crop, dst, transform, mdpFlags);
   1688         //Configure rotator for pre-rotation
   1689         if(configRotator(*rot, whf, crop, mdpFlags, orient, downscale) < 0) {
   1690             ALOGE("%s: configRotator failed!", __FUNCTION__);
   1691             return -1;
   1692         }
   1693         updateSource(orient, whf, crop, *rot);
   1694         rotFlags |= ovutils::ROT_PREROTATED;
   1695     }
   1696 
   1697     //For the mdp, since either we are pre-rotating or MDP does flips
   1698     orient = OVERLAY_TRANSFORM_0;
   1699     transform = 0;
   1700     PipeArgs parg(mdpFlags, whf, z, isFg,
   1701                   static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
   1702                   (ovutils::eBlending) getBlending(layer->blending));
   1703 
   1704     if(configMdp(ctx->mOverlay, parg, orient, crop, dst, metadata, dest) < 0) {
   1705         ALOGE("%s: commit failed for low res panel", __FUNCTION__);
   1706         return -1;
   1707     }
   1708     return 0;
   1709 }
   1710 
   1711 //Helper to 1) Ensure crops dont have gaps 2) Ensure L and W are even
   1712 void sanitizeSourceCrop(hwc_rect_t& cropL, hwc_rect_t& cropR,
   1713         private_handle_t *hnd) {
   1714     if(cropL.right - cropL.left) {
   1715         if(isYuvBuffer(hnd)) {
   1716             //Always safe to even down left
   1717             ovutils::even_floor(cropL.left);
   1718             //If right is even, automatically width is even, since left is
   1719             //already even
   1720             ovutils::even_floor(cropL.right);
   1721         }
   1722         //Make sure there are no gaps between left and right splits if the layer
   1723         //is spread across BOTH halves
   1724         if(cropR.right - cropR.left) {
   1725             cropR.left = cropL.right;
   1726         }
   1727     }
   1728 
   1729     if(cropR.right - cropR.left) {
   1730         if(isYuvBuffer(hnd)) {
   1731             //Always safe to even down left
   1732             ovutils::even_floor(cropR.left);
   1733             //If right is even, automatically width is even, since left is
   1734             //already even
   1735             ovutils::even_floor(cropR.right);
   1736         }
   1737     }
   1738 }
   1739 
   1740 int configureSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
   1741         const int& dpy, eMdpFlags& mdpFlagsL, eZorder& z,
   1742         eIsFg& isFg, const eDest& lDest, const eDest& rDest,
   1743         Rotator **rot) {
   1744     private_handle_t *hnd = (private_handle_t *)layer->handle;
   1745     if(!hnd) {
   1746         ALOGE("%s: layer handle is NULL", __FUNCTION__);
   1747         return -1;
   1748     }
   1749 
   1750     MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
   1751 
   1752     int hw_w = ctx->dpyAttr[dpy].xres;
   1753     int hw_h = ctx->dpyAttr[dpy].yres;
   1754     hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
   1755     hwc_rect_t dst = layer->displayFrame;
   1756     int transform = layer->transform;
   1757     eTransform orient = static_cast<eTransform>(transform);
   1758     const int downscale = 0;
   1759     int rotFlags = ROT_FLAGS_NONE;
   1760     uint32_t format = ovutils::getMdpFormat(hnd->format, isTileRendered(hnd));
   1761     Whf whf(getWidth(hnd), getHeight(hnd), format, (uint32_t)hnd->size);
   1762 
   1763     // Handle R/B swap
   1764     if (layer->flags & HWC_FORMAT_RB_SWAP) {
   1765         if (hnd->format == HAL_PIXEL_FORMAT_RGBA_8888)
   1766             whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRA_8888);
   1767         else if (hnd->format == HAL_PIXEL_FORMAT_RGBX_8888)
   1768             whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRX_8888);
   1769     }
   1770 
   1771     /* Calculate the external display position based on MDP downscale,
   1772        ActionSafe, and extorientation features. */
   1773     calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient);
   1774 
   1775     setMdpFlags(ctx, layer, mdpFlagsL, 0, transform);
   1776 
   1777     if(lDest != OV_INVALID && rDest != OV_INVALID) {
   1778         //Enable overfetch
   1779         setMdpFlags(mdpFlagsL, OV_MDSS_MDP_DUAL_PIPE);
   1780     }
   1781 
   1782     //Will do something only if feature enabled and conditions suitable
   1783     //hollow call otherwise
   1784     if(ctx->mAD->prepare(ctx, crop, whf, hnd)) {
   1785         overlay::Writeback *wb = overlay::Writeback::getInstance();
   1786         whf.format = wb->getOutputFormat();
   1787     }
   1788 
   1789     if(has90Transform(layer) && isRotationDoable(ctx, hnd)) {
   1790         (*rot) = ctx->mRotMgr->getNext();
   1791         if((*rot) == NULL) return -1;
   1792         ctx->mLayerRotMap[dpy]->add(layer, *rot);
   1793         //Configure rotator for pre-rotation
   1794         if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale) < 0) {
   1795             ALOGE("%s: configRotator failed!", __FUNCTION__);
   1796             return -1;
   1797         }
   1798         updateSource(orient, whf, crop, *rot);
   1799         rotFlags |= ROT_PREROTATED;
   1800     }
   1801 
   1802     eMdpFlags mdpFlagsR = mdpFlagsL;
   1803     setMdpFlags(mdpFlagsR, OV_MDSS_MDP_RIGHT_MIXER);
   1804 
   1805     hwc_rect_t tmp_cropL = {0}, tmp_dstL = {0};
   1806     hwc_rect_t tmp_cropR = {0}, tmp_dstR = {0};
   1807 
   1808     const int lSplit = getLeftSplit(ctx, dpy);
   1809 
   1810     // Calculate Left rects
   1811     if(dst.left < lSplit) {
   1812         tmp_cropL = crop;
   1813         tmp_dstL = dst;
   1814         hwc_rect_t scissor = {0, 0, lSplit, hw_h };
   1815         scissor = getIntersection(ctx->mViewFrame[dpy], scissor);
   1816         qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
   1817     }
   1818 
   1819     // Calculate Right rects
   1820     if(dst.right > lSplit) {
   1821         tmp_cropR = crop;
   1822         tmp_dstR = dst;
   1823         hwc_rect_t scissor = {lSplit, 0, hw_w, hw_h };
   1824         scissor = getIntersection(ctx->mViewFrame[dpy], scissor);
   1825         qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
   1826     }
   1827 
   1828     sanitizeSourceCrop(tmp_cropL, tmp_cropR, hnd);
   1829 
   1830     //When buffer is H-flipped, contents of mixer config also needs to swapped
   1831     //Not needed if the layer is confined to one half of the screen.
   1832     //If rotator has been used then it has also done the flips, so ignore them.
   1833     if((orient & OVERLAY_TRANSFORM_FLIP_H) && (dst.left < lSplit) &&
   1834             (dst.right > lSplit) && (*rot) == NULL) {
   1835         hwc_rect_t new_cropR;
   1836         new_cropR.left = tmp_cropL.left;
   1837         new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
   1838 
   1839         hwc_rect_t new_cropL;
   1840         new_cropL.left  = new_cropR.right;
   1841         new_cropL.right = tmp_cropR.right;
   1842 
   1843         tmp_cropL.left =  new_cropL.left;
   1844         tmp_cropL.right =  new_cropL.right;
   1845 
   1846         tmp_cropR.left = new_cropR.left;
   1847         tmp_cropR.right =  new_cropR.right;
   1848 
   1849     }
   1850 
   1851     //For the mdp, since either we are pre-rotating or MDP does flips
   1852     orient = OVERLAY_TRANSFORM_0;
   1853     transform = 0;
   1854 
   1855     //configure left mixer
   1856     if(lDest != OV_INVALID) {
   1857         PipeArgs pargL(mdpFlagsL, whf, z, isFg,
   1858                        static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
   1859                        (ovutils::eBlending) getBlending(layer->blending));
   1860 
   1861         if(configMdp(ctx->mOverlay, pargL, orient,
   1862                 tmp_cropL, tmp_dstL, metadata, lDest) < 0) {
   1863             ALOGE("%s: commit failed for left mixer config", __FUNCTION__);
   1864             return -1;
   1865         }
   1866     }
   1867 
   1868     //configure right mixer
   1869     if(rDest != OV_INVALID) {
   1870         PipeArgs pargR(mdpFlagsR, whf, z, isFg,
   1871                        static_cast<eRotFlags>(rotFlags),
   1872                        layer->planeAlpha,
   1873                        (ovutils::eBlending) getBlending(layer->blending));
   1874         tmp_dstR.right = tmp_dstR.right - lSplit;
   1875         tmp_dstR.left = tmp_dstR.left - lSplit;
   1876         if(configMdp(ctx->mOverlay, pargR, orient,
   1877                 tmp_cropR, tmp_dstR, metadata, rDest) < 0) {
   1878             ALOGE("%s: commit failed for right mixer config", __FUNCTION__);
   1879             return -1;
   1880         }
   1881     }
   1882 
   1883     return 0;
   1884 }
   1885 
   1886 int configureSourceSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
   1887         const int& dpy, eMdpFlags& mdpFlagsL, eZorder& z,
   1888         eIsFg& isFg, const eDest& lDest, const eDest& rDest,
   1889         Rotator **rot) {
   1890     private_handle_t *hnd = (private_handle_t *)layer->handle;
   1891     if(!hnd) {
   1892         ALOGE("%s: layer handle is NULL", __FUNCTION__);
   1893         return -1;
   1894     }
   1895 
   1896     MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
   1897 
   1898     hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);;
   1899     hwc_rect_t dst = layer->displayFrame;
   1900     int transform = layer->transform;
   1901     eTransform orient = static_cast<eTransform>(transform);
   1902     const int downscale = 0;
   1903     int rotFlags = ROT_FLAGS_NONE;
   1904     //Splitting only YUV layer on primary panel needs different zorders
   1905     //for both layers as both the layers are configured to single mixer
   1906     eZorder lz = z;
   1907     eZorder rz = (eZorder)(z + 1);
   1908 
   1909     Whf whf(getWidth(hnd), getHeight(hnd),
   1910             getMdpFormat(hnd->format), (uint32_t)hnd->size);
   1911 
   1912     /* Calculate the external display position based on MDP downscale,
   1913        ActionSafe, and extorientation features. */
   1914     calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient);
   1915 
   1916     setMdpFlags(ctx, layer, mdpFlagsL, 0, transform);
   1917     trimLayer(ctx, dpy, transform, crop, dst);
   1918 
   1919     if(has90Transform(layer) && isRotationDoable(ctx, hnd)) {
   1920         (*rot) = ctx->mRotMgr->getNext();
   1921         if((*rot) == NULL) return -1;
   1922         ctx->mLayerRotMap[dpy]->add(layer, *rot);
   1923         // BWC is not tested for other formats So enable it only for YUV format
   1924         if(!dpy && isYuvBuffer(hnd))
   1925             BwcPM::setBwc(crop, dst, transform, mdpFlagsL);
   1926         //Configure rotator for pre-rotation
   1927         if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale) < 0) {
   1928             ALOGE("%s: configRotator failed!", __FUNCTION__);
   1929             return -1;
   1930         }
   1931         updateSource(orient, whf, crop, *rot);
   1932         rotFlags |= ROT_PREROTATED;
   1933     }
   1934 
   1935     eMdpFlags mdpFlagsR = mdpFlagsL;
   1936     int lSplit = dst.left + (dst.right - dst.left)/2;
   1937 
   1938     hwc_rect_t tmp_cropL = {0}, tmp_dstL = {0};
   1939     hwc_rect_t tmp_cropR = {0}, tmp_dstR = {0};
   1940 
   1941     if(lDest != OV_INVALID) {
   1942         tmp_cropL = crop;
   1943         tmp_dstL = dst;
   1944         hwc_rect_t scissor = {dst.left, dst.top, lSplit, dst.bottom };
   1945         qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
   1946     }
   1947     if(rDest != OV_INVALID) {
   1948         tmp_cropR = crop;
   1949         tmp_dstR = dst;
   1950         hwc_rect_t scissor = {lSplit, dst.top, dst.right, dst.bottom };
   1951         qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
   1952     }
   1953 
   1954     sanitizeSourceCrop(tmp_cropL, tmp_cropR, hnd);
   1955 
   1956     //When buffer is H-flipped, contents of mixer config also needs to swapped
   1957     //Not needed if the layer is confined to one half of the screen.
   1958     //If rotator has been used then it has also done the flips, so ignore them.
   1959     if((orient & OVERLAY_TRANSFORM_FLIP_H) && lDest != OV_INVALID
   1960             && rDest != OV_INVALID && (*rot) == NULL) {
   1961         hwc_rect_t new_cropR;
   1962         new_cropR.left = tmp_cropL.left;
   1963         new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
   1964 
   1965         hwc_rect_t new_cropL;
   1966         new_cropL.left  = new_cropR.right;
   1967         new_cropL.right = tmp_cropR.right;
   1968 
   1969         tmp_cropL.left =  new_cropL.left;
   1970         tmp_cropL.right =  new_cropL.right;
   1971 
   1972         tmp_cropR.left = new_cropR.left;
   1973         tmp_cropR.right =  new_cropR.right;
   1974 
   1975     }
   1976 
   1977     //For the mdp, since either we are pre-rotating or MDP does flips
   1978     orient = OVERLAY_TRANSFORM_0;
   1979     transform = 0;
   1980 
   1981     //configure left half
   1982     if(lDest != OV_INVALID) {
   1983         PipeArgs pargL(mdpFlagsL, whf, lz, isFg,
   1984                 static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
   1985                 (ovutils::eBlending) getBlending(layer->blending));
   1986 
   1987         if(configMdp(ctx->mOverlay, pargL, orient,
   1988                     tmp_cropL, tmp_dstL, metadata, lDest) < 0) {
   1989             ALOGE("%s: commit failed for left half config", __FUNCTION__);
   1990             return -1;
   1991         }
   1992     }
   1993 
   1994     //configure right half
   1995     if(rDest != OV_INVALID) {
   1996         PipeArgs pargR(mdpFlagsR, whf, rz, isFg,
   1997                 static_cast<eRotFlags>(rotFlags),
   1998                 layer->planeAlpha,
   1999                 (ovutils::eBlending) getBlending(layer->blending));
   2000         if(configMdp(ctx->mOverlay, pargR, orient,
   2001                     tmp_cropR, tmp_dstR, metadata, rDest) < 0) {
   2002             ALOGE("%s: commit failed for right half config", __FUNCTION__);
   2003             return -1;
   2004         }
   2005     }
   2006 
   2007     return 0;
   2008 }
   2009 
   2010 bool canUseRotator(hwc_context_t *ctx, int dpy) {
   2011     if(ctx->mOverlay->isDMAMultiplexingSupported() &&
   2012             isSecondaryConnected(ctx) &&
   2013             !ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].isPause) {
   2014         /* mdss driver on certain targets support multiplexing of DMA pipe
   2015          * in LINE and BLOCK modes for writeback panels.
   2016          */
   2017         if(dpy == HWC_DISPLAY_PRIMARY)
   2018             return false;
   2019     }
   2020     if(ctx->mMDP.version == qdutils::MDP_V3_0_4)
   2021         return false;
   2022     return true;
   2023 }
   2024 
   2025 int getLeftSplit(hwc_context_t *ctx, const int& dpy) {
   2026     //Default even split for all displays with high res
   2027     int lSplit = ctx->dpyAttr[dpy].xres / 2;
   2028     if(dpy == HWC_DISPLAY_PRIMARY &&
   2029             qdutils::MDPVersion::getInstance().getLeftSplit()) {
   2030         //Override if split published by driver for primary
   2031         lSplit = qdutils::MDPVersion::getInstance().getLeftSplit();
   2032     }
   2033     return lSplit;
   2034 }
   2035 
   2036 bool isDisplaySplit(hwc_context_t* ctx, int dpy) {
   2037     if(ctx->dpyAttr[dpy].xres > qdutils::MAX_DISPLAY_DIM) {
   2038         return true;
   2039     }
   2040     //For testing we could split primary via device tree values
   2041     if(dpy == HWC_DISPLAY_PRIMARY &&
   2042         qdutils::MDPVersion::getInstance().getRightSplit()) {
   2043         return true;
   2044     }
   2045     return false;
   2046 }
   2047 
   2048 //clear prev layer prop flags and realloc for current frame
   2049 void reset_layer_prop(hwc_context_t* ctx, int dpy, int numAppLayers) {
   2050     if(ctx->layerProp[dpy]) {
   2051        delete[] ctx->layerProp[dpy];
   2052        ctx->layerProp[dpy] = NULL;
   2053     }
   2054     ctx->layerProp[dpy] = new LayerProp[numAppLayers];
   2055 }
   2056 
   2057 bool isAbcInUse(hwc_context_t *ctx){
   2058   return (ctx->enableABC && ctx->listStats[0].renderBufIndexforABC == 0);
   2059 }
   2060 
   2061 void dumpBuffer(private_handle_t *ohnd, char *bufferName) {
   2062     if (ohnd != NULL && ohnd->base) {
   2063         char dumpFilename[PATH_MAX];
   2064         bool bResult = false;
   2065         snprintf(dumpFilename, sizeof(dumpFilename), "/data/%s.%s.%dx%d.raw",
   2066             bufferName,
   2067             overlay::utils::getFormatString(utils::getMdpFormat(ohnd->format)),
   2068             getWidth(ohnd), getHeight(ohnd));
   2069         FILE* fp = fopen(dumpFilename, "w+");
   2070         if (NULL != fp) {
   2071             bResult = (bool) fwrite((void*)ohnd->base, ohnd->size, 1, fp);
   2072             fclose(fp);
   2073         }
   2074         ALOGD("Buffer[%s] Dump to %s: %s",
   2075         bufferName, dumpFilename, bResult ? "Success" : "Fail");
   2076     }
   2077 }
   2078 
   2079 bool isGLESComp(hwc_context_t *ctx,
   2080                      hwc_display_contents_1_t* list) {
   2081     int numAppLayers = ctx->listStats[HWC_DISPLAY_PRIMARY].numAppLayers;
   2082     for(int index = 0; index < numAppLayers; index++) {
   2083         hwc_layer_1_t* layer = &(list->hwLayers[index]);
   2084         if(layer->compositionType == HWC_FRAMEBUFFER)
   2085             return true;
   2086     }
   2087     return false;
   2088 }
   2089 
   2090 void setGPUHint(hwc_context_t* ctx, hwc_display_contents_1_t* list) {
   2091     struct gpu_hint_info *gpuHint = &ctx->mGPUHintInfo;
   2092     if(!gpuHint->mGpuPerfModeEnable || !ctx || !list)
   2093         return;
   2094 
   2095 #ifdef QCOM_BSP
   2096     /* Set the GPU hint flag to high for MIXED/GPU composition only for
   2097        first frame after MDP -> GPU/MIXED mode transition. Set the GPU
   2098        hint to default if the previous composition is GPU or current GPU
   2099        composition is due to idle fallback */
   2100     if(!gpuHint->mEGLDisplay || !gpuHint->mEGLContext) {
   2101         gpuHint->mEGLDisplay = eglGetCurrentDisplay();
   2102         if(!gpuHint->mEGLDisplay) {
   2103             ALOGW("%s Warning: EGL current display is NULL", __FUNCTION__);
   2104             return;
   2105         }
   2106         gpuHint->mEGLContext = eglGetCurrentContext();
   2107         if(!gpuHint->mEGLContext) {
   2108             ALOGW("%s Warning: EGL current context is NULL", __FUNCTION__);
   2109             return;
   2110         }
   2111     }
   2112     if(isGLESComp(ctx, list)) {
   2113         if(gpuHint->mCompositionState != COMPOSITION_STATE_GPU
   2114             && !MDPComp::isIdleFallback()) {
   2115             EGLint attr_list[] = {EGL_GPU_HINT_1,
   2116                                   EGL_GPU_LEVEL_3,
   2117                                   EGL_NONE };
   2118             if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_3) &&
   2119                 !eglGpuPerfHintQCOM(gpuHint->mEGLDisplay,
   2120                                     gpuHint->mEGLContext, attr_list)) {
   2121                 ALOGW("eglGpuPerfHintQCOM failed for Built in display");
   2122             } else {
   2123                 gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_3;
   2124                 gpuHint->mCompositionState = COMPOSITION_STATE_GPU;
   2125             }
   2126         } else {
   2127             EGLint attr_list[] = {EGL_GPU_HINT_1,
   2128                                   EGL_GPU_LEVEL_0,
   2129                                   EGL_NONE };
   2130             if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_0) &&
   2131                 !eglGpuPerfHintQCOM(gpuHint->mEGLDisplay,
   2132                                     gpuHint->mEGLContext, attr_list)) {
   2133                 ALOGW("eglGpuPerfHintQCOM failed for Built in display");
   2134             } else {
   2135                 gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_0;
   2136             }
   2137             if(MDPComp::isIdleFallback()) {
   2138                 gpuHint->mCompositionState = COMPOSITION_STATE_IDLE_FALLBACK;
   2139             }
   2140         }
   2141     } else {
   2142         /* set the GPU hint flag to default for MDP composition */
   2143         EGLint attr_list[] = {EGL_GPU_HINT_1,
   2144                               EGL_GPU_LEVEL_0,
   2145                               EGL_NONE };
   2146         if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_0) &&
   2147                 !eglGpuPerfHintQCOM(gpuHint->mEGLDisplay,
   2148                                     gpuHint->mEGLContext, attr_list)) {
   2149             ALOGW("eglGpuPerfHintQCOM failed for Built in display");
   2150         } else {
   2151             gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_0;
   2152         }
   2153         gpuHint->mCompositionState = COMPOSITION_STATE_MDP;
   2154     }
   2155 #endif
   2156 }
   2157 
   2158 bool isPeripheral(const hwc_rect_t& rect1, const hwc_rect_t& rect2) {
   2159     // To be peripheral, 3 boundaries should match.
   2160     uint8_t eqBounds = 0;
   2161     if (rect1.left == rect2.left)
   2162         eqBounds++;
   2163     if (rect1.top == rect2.top)
   2164         eqBounds++;
   2165     if (rect1.right == rect2.right)
   2166         eqBounds++;
   2167     if (rect1.bottom == rect2.bottom)
   2168         eqBounds++;
   2169     return (eqBounds == 3);
   2170 }
   2171 
   2172 void BwcPM::setBwc(const hwc_rect_t& crop,
   2173             const hwc_rect_t& dst, const int& transform,
   2174             ovutils::eMdpFlags& mdpFlags) {
   2175     //Target doesnt support Bwc
   2176     if(!qdutils::MDPVersion::getInstance().supportsBWC()) {
   2177         return;
   2178     }
   2179     int src_w = crop.right - crop.left;
   2180     int src_h = crop.bottom - crop.top;
   2181     int dst_w = dst.right - dst.left;
   2182     int dst_h = dst.bottom - dst.top;
   2183     if(transform & HAL_TRANSFORM_ROT_90) {
   2184         swap(src_w, src_h);
   2185     }
   2186     //src width > MAX mixer supported dim
   2187     if(src_w > qdutils::MAX_DISPLAY_DIM) {
   2188         return;
   2189     }
   2190     //Decimation necessary, cannot use BWC. H/W requirement.
   2191     if(qdutils::MDPVersion::getInstance().supportsDecimation()) {
   2192         uint8_t horzDeci = 0;
   2193         uint8_t vertDeci = 0;
   2194         ovutils::getDecimationFactor(src_w, src_h, dst_w, dst_h, horzDeci,
   2195                 vertDeci);
   2196         if(horzDeci || vertDeci) return;
   2197     }
   2198     //Property
   2199     char value[PROPERTY_VALUE_MAX];
   2200     property_get("debug.disable.bwc", value, "0");
   2201      if(atoi(value)) return;
   2202 
   2203     ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDSS_MDP_BWC_EN);
   2204 }
   2205 
   2206 void LayerRotMap::add(hwc_layer_1_t* layer, Rotator *rot) {
   2207     if(mCount >= MAX_SESS) return;
   2208     mLayer[mCount] = layer;
   2209     mRot[mCount] = rot;
   2210     mCount++;
   2211 }
   2212 
   2213 void LayerRotMap::reset() {
   2214     for (int i = 0; i < MAX_SESS; i++) {
   2215         mLayer[i] = 0;
   2216         mRot[i] = 0;
   2217     }
   2218     mCount = 0;
   2219 }
   2220 
   2221 void LayerRotMap::clear() {
   2222     RotMgr::getInstance()->markUnusedTop(mCount);
   2223     reset();
   2224 }
   2225 
   2226 void LayerRotMap::setReleaseFd(const int& fence) {
   2227     for(uint32_t i = 0; i < mCount; i++) {
   2228         mRot[i]->setReleaseFd(dup(fence));
   2229     }
   2230 }
   2231 
   2232 void resetROI(hwc_context_t *ctx, const int dpy) {
   2233     const int fbXRes = (int)ctx->dpyAttr[dpy].xres;
   2234     const int fbYRes = (int)ctx->dpyAttr[dpy].yres;
   2235     if(isDisplaySplit(ctx, dpy)) {
   2236         const int lSplit = getLeftSplit(ctx, dpy);
   2237         ctx->listStats[dpy].lRoi = (struct hwc_rect){0, 0, lSplit, fbYRes};
   2238         ctx->listStats[dpy].rRoi = (struct hwc_rect){lSplit, 0, fbXRes, fbYRes};
   2239     } else  {
   2240         ctx->listStats[dpy].lRoi = (struct hwc_rect){0, 0,fbXRes, fbYRes};
   2241         ctx->listStats[dpy].rRoi = (struct hwc_rect){0, 0, 0, 0};
   2242     }
   2243 }
   2244 
   2245 hwc_rect_t getSanitizeROI(struct hwc_rect roi, hwc_rect boundary)
   2246 {
   2247    if(!isValidRect(roi))
   2248       return roi;
   2249 
   2250    struct hwc_rect t_roi = roi;
   2251 
   2252    const int LEFT_ALIGN = qdutils::MDPVersion::getInstance().getLeftAlign();
   2253    const int WIDTH_ALIGN = qdutils::MDPVersion::getInstance().getWidthAlign();
   2254    const int TOP_ALIGN = qdutils::MDPVersion::getInstance().getTopAlign();
   2255    const int HEIGHT_ALIGN = qdutils::MDPVersion::getInstance().getHeightAlign();
   2256    const int MIN_WIDTH = qdutils::MDPVersion::getInstance().getMinROIWidth();
   2257    const int MIN_HEIGHT = qdutils::MDPVersion::getInstance().getMinROIHeight();
   2258 
   2259    /* Align to minimum width recommended by the panel */
   2260    if((t_roi.right - t_roi.left) < MIN_WIDTH) {
   2261        if((t_roi.left + MIN_WIDTH) > boundary.right)
   2262            t_roi.left = t_roi.right - MIN_WIDTH;
   2263        else
   2264            t_roi.right = t_roi.left + MIN_WIDTH;
   2265    }
   2266 
   2267   /* Align to minimum height recommended by the panel */
   2268    if((t_roi.bottom - t_roi.top) < MIN_HEIGHT) {
   2269        if((t_roi.top + MIN_HEIGHT) > boundary.bottom)
   2270            t_roi.top = t_roi.bottom - MIN_HEIGHT;
   2271        else
   2272            t_roi.bottom = t_roi.top + MIN_HEIGHT;
   2273    }
   2274 
   2275    /* Align left and width to meet panel restrictions */
   2276    if(LEFT_ALIGN)
   2277        t_roi.left = t_roi.left - (t_roi.left % LEFT_ALIGN);
   2278 
   2279    if(WIDTH_ALIGN) {
   2280        int width = t_roi.right - t_roi.left;
   2281        width = WIDTH_ALIGN * ((width + (WIDTH_ALIGN - 1)) / WIDTH_ALIGN);
   2282        t_roi.right = t_roi.left + width;
   2283 
   2284        if(t_roi.right > boundary.right) {
   2285            t_roi.right = boundary.right;
   2286            t_roi.left = t_roi.right - width;
   2287 
   2288            if(LEFT_ALIGN)
   2289                t_roi.left = t_roi.left - (t_roi.left % LEFT_ALIGN);
   2290        }
   2291    }
   2292 
   2293 
   2294    /* Align top and height to meet panel restrictions */
   2295    if(TOP_ALIGN)
   2296        t_roi.top = t_roi.top - (t_roi.top % TOP_ALIGN);
   2297 
   2298    if(HEIGHT_ALIGN) {
   2299        int height = t_roi.bottom - t_roi.top;
   2300        height = HEIGHT_ALIGN *  ((height + (HEIGHT_ALIGN - 1)) / HEIGHT_ALIGN);
   2301        t_roi.bottom = t_roi.top  + height;
   2302 
   2303        if(t_roi.bottom > boundary.bottom) {
   2304            t_roi.bottom = boundary.bottom;
   2305            t_roi.top = t_roi.bottom - height;
   2306 
   2307            if(TOP_ALIGN)
   2308                t_roi.top = t_roi.top - (t_roi.top % TOP_ALIGN);
   2309        }
   2310    }
   2311 
   2312 
   2313    return t_roi;
   2314 }
   2315 
   2316 };//namespace qhwc
   2317