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