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