hwc_utils.cpp revision 5bbc98fa2dcc744a1943cc8c85ce74169fc8a044
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].secureUI = false;
836    ctx->listStats[dpy].yuv4k2kCount = 0;
837    ctx->mViewFrame[dpy] = (hwc_rect_t){0, 0, 0, 0};
838    ctx->dpyAttr[dpy].mActionSafePresent = isActionSafePresent(ctx, dpy);
839
840    resetROI(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 isSameRect(const hwc_rect& rect1, const hwc_rect& rect2)
1072{
1073   return ((rect1.left == rect2.left) && (rect1.top == rect2.top) &&
1074           (rect1.right == rect2.right) && (rect1.bottom == rect2.bottom));
1075}
1076
1077bool isValidRect(const hwc_rect& rect)
1078{
1079   return ((rect.bottom > rect.top) && (rect.right > rect.left)) ;
1080}
1081
1082bool operator ==(const hwc_rect_t& lhs, const hwc_rect_t& rhs) {
1083    if(lhs.left == rhs.left && lhs.top == rhs.top &&
1084       lhs.right == rhs.right &&  lhs.bottom == rhs.bottom )
1085          return true ;
1086    return false;
1087}
1088
1089hwc_rect_t moveRect(const hwc_rect_t& rect, const int& x_off, const int& y_off)
1090{
1091    hwc_rect_t res;
1092
1093    if(!isValidRect(rect))
1094        return (hwc_rect_t){0, 0, 0, 0};
1095
1096    res.left = rect.left + x_off;
1097    res.top = rect.top + y_off;
1098    res.right = rect.right + x_off;
1099    res.bottom = rect.bottom + y_off;
1100
1101    return res;
1102}
1103
1104/* computes the intersection of two rects */
1105hwc_rect_t getIntersection(const hwc_rect_t& rect1, const hwc_rect_t& rect2)
1106{
1107   hwc_rect_t res;
1108
1109   if(!isValidRect(rect1) || !isValidRect(rect2)){
1110      return (hwc_rect_t){0, 0, 0, 0};
1111   }
1112
1113
1114   res.left = max(rect1.left, rect2.left);
1115   res.top = max(rect1.top, rect2.top);
1116   res.right = min(rect1.right, rect2.right);
1117   res.bottom = min(rect1.bottom, rect2.bottom);
1118
1119   if(!isValidRect(res))
1120      return (hwc_rect_t){0, 0, 0, 0};
1121
1122   return res;
1123}
1124
1125/* computes the union of two rects */
1126hwc_rect_t getUnion(const hwc_rect &rect1, const hwc_rect &rect2)
1127{
1128   hwc_rect_t res;
1129
1130   if(!isValidRect(rect1)){
1131      return rect2;
1132   }
1133
1134   if(!isValidRect(rect2)){
1135      return rect1;
1136   }
1137
1138   res.left = min(rect1.left, rect2.left);
1139   res.top = min(rect1.top, rect2.top);
1140   res.right =  max(rect1.right, rect2.right);
1141   res.bottom =  max(rect1.bottom, rect2.bottom);
1142
1143   return res;
1144}
1145
1146/* Not a geometrical rect deduction. Deducts rect2 from rect1 only if it results
1147 * a single rect */
1148hwc_rect_t deductRect(const hwc_rect_t& rect1, const hwc_rect_t& rect2) {
1149
1150   hwc_rect_t res = rect1;
1151
1152   if((rect1.left == rect2.left) && (rect1.right == rect2.right)) {
1153      if((rect1.top == rect2.top) && (rect2.bottom <= rect1.bottom))
1154         res.top = rect2.bottom;
1155      else if((rect1.bottom == rect2.bottom)&& (rect2.top >= rect1.top))
1156         res.bottom = rect2.top;
1157   }
1158   else if((rect1.top == rect2.top) && (rect1.bottom == rect2.bottom)) {
1159      if((rect1.left == rect2.left) && (rect2.right <= rect1.right))
1160         res.left = rect2.right;
1161      else if((rect1.right == rect2.right)&& (rect2.left >= rect1.left))
1162         res.right = rect2.left;
1163   }
1164   return res;
1165}
1166
1167void optimizeLayerRects(const hwc_display_contents_1_t *list) {
1168    int i= (int)list->numHwLayers-2;
1169    while(i > 0) {
1170        //see if there is no blending required.
1171        //If it is opaque see if we can substract this region from below
1172        //layers.
1173        if(list->hwLayers[i].blending == HWC_BLENDING_NONE) {
1174            int j= i-1;
1175            hwc_rect_t& topframe =
1176                (hwc_rect_t&)list->hwLayers[i].displayFrame;
1177            while(j >= 0) {
1178               if(!needsScaling(&list->hwLayers[j])) {
1179                  hwc_layer_1_t* layer = (hwc_layer_1_t*)&list->hwLayers[j];
1180                  hwc_rect_t& bottomframe = layer->displayFrame;
1181                  hwc_rect_t bottomCrop =
1182                      integerizeSourceCrop(layer->sourceCropf);
1183                  int transform =layer->transform;
1184
1185                  hwc_rect_t irect = getIntersection(bottomframe, topframe);
1186                  if(isValidRect(irect)) {
1187                     hwc_rect_t dest_rect;
1188                     //if intersection is valid rect, deduct it
1189                     dest_rect  = deductRect(bottomframe, irect);
1190                     qhwc::calculate_crop_rects(bottomCrop, bottomframe,
1191                                                dest_rect, transform);
1192                     //Update layer sourceCropf
1193                     layer->sourceCropf.left =(float)bottomCrop.left;
1194                     layer->sourceCropf.top = (float)bottomCrop.top;
1195                     layer->sourceCropf.right = (float)bottomCrop.right;
1196                     layer->sourceCropf.bottom = (float)bottomCrop.bottom;
1197#ifdef QCOM_BSP
1198                     //Update layer dirtyRect
1199                     layer->dirtyRect = getIntersection(bottomCrop,
1200                                            layer->dirtyRect);
1201#endif
1202                  }
1203               }
1204               j--;
1205            }
1206        }
1207        i--;
1208    }
1209}
1210
1211void getNonWormholeRegion(hwc_display_contents_1_t* list,
1212                              hwc_rect_t& nwr)
1213{
1214    size_t last = list->numHwLayers - 1;
1215    hwc_rect_t fbDisplayFrame = list->hwLayers[last].displayFrame;
1216    //Initiliaze nwr to first frame
1217    nwr.left =  list->hwLayers[0].displayFrame.left;
1218    nwr.top =  list->hwLayers[0].displayFrame.top;
1219    nwr.right =  list->hwLayers[0].displayFrame.right;
1220    nwr.bottom =  list->hwLayers[0].displayFrame.bottom;
1221
1222    for (size_t i = 1; i < last; i++) {
1223        hwc_rect_t displayFrame = list->hwLayers[i].displayFrame;
1224        nwr = getUnion(nwr, displayFrame);
1225    }
1226
1227    //Intersect with the framebuffer
1228    nwr = getIntersection(nwr, fbDisplayFrame);
1229}
1230
1231bool isExternalActive(hwc_context_t* ctx) {
1232    return ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].isActive;
1233}
1234
1235void closeAcquireFds(hwc_display_contents_1_t* list) {
1236    if(LIKELY(list)) {
1237        for(uint32_t i = 0; i < list->numHwLayers; i++) {
1238            //Close the acquireFenceFds
1239            //HWC_FRAMEBUFFER are -1 already by SF, rest we close.
1240            if(list->hwLayers[i].acquireFenceFd >= 0) {
1241                close(list->hwLayers[i].acquireFenceFd);
1242                list->hwLayers[i].acquireFenceFd = -1;
1243            }
1244        }
1245        //Writeback
1246        if(list->outbufAcquireFenceFd >= 0) {
1247            close(list->outbufAcquireFenceFd);
1248            list->outbufAcquireFenceFd = -1;
1249        }
1250    }
1251}
1252
1253int hwc_sync(hwc_context_t *ctx, hwc_display_contents_1_t* list, int dpy,
1254        int fd) {
1255    ATRACE_CALL();
1256    int ret = 0;
1257    int acquireFd[MAX_NUM_APP_LAYERS];
1258    int count = 0;
1259    int releaseFd = -1;
1260    int retireFd = -1;
1261    int fbFd = -1;
1262    bool swapzero = false;
1263
1264    struct mdp_buf_sync data;
1265    memset(&data, 0, sizeof(data));
1266    data.acq_fen_fd = acquireFd;
1267    data.rel_fen_fd = &releaseFd;
1268    data.retire_fen_fd = &retireFd;
1269    data.flags = MDP_BUF_SYNC_FLAG_RETIRE_FENCE;
1270
1271    char property[PROPERTY_VALUE_MAX];
1272    if(property_get("debug.egl.swapinterval", property, "1") > 0) {
1273        if(atoi(property) == 0)
1274            swapzero = true;
1275    }
1276
1277    bool isExtAnimating = false;
1278    if(dpy)
1279       isExtAnimating = ctx->listStats[dpy].isDisplayAnimating;
1280
1281    //Send acquireFenceFds to rotator
1282    for(uint32_t i = 0; i < ctx->mLayerRotMap[dpy]->getCount(); i++) {
1283        int rotFd = ctx->mRotMgr->getRotDevFd();
1284        int rotReleaseFd = -1;
1285        overlay::Rotator* currRot = ctx->mLayerRotMap[dpy]->getRot(i);
1286        hwc_layer_1_t* currLayer = ctx->mLayerRotMap[dpy]->getLayer(i);
1287        if((currRot == NULL) || (currLayer == NULL)) {
1288            continue;
1289        }
1290        struct mdp_buf_sync rotData;
1291        memset(&rotData, 0, sizeof(rotData));
1292        rotData.acq_fen_fd =
1293                &currLayer->acquireFenceFd;
1294        rotData.rel_fen_fd = &rotReleaseFd; //driver to populate this
1295        rotData.session_id = currRot->getSessId();
1296        if(currLayer->acquireFenceFd >= 0) {
1297            rotData.acq_fen_fd_cnt = 1; //1 ioctl call per rot session
1298        }
1299        int ret = 0;
1300        ret = ioctl(rotFd, MSMFB_BUFFER_SYNC, &rotData);
1301        if(ret < 0) {
1302            ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed for rot sync, err=%s",
1303                    __FUNCTION__, strerror(errno));
1304        } else {
1305            close(currLayer->acquireFenceFd);
1306            //For MDP to wait on.
1307            currLayer->acquireFenceFd =
1308                    dup(rotReleaseFd);
1309            //A buffer is free to be used by producer as soon as its copied to
1310            //rotator
1311            currLayer->releaseFenceFd =
1312                    rotReleaseFd;
1313        }
1314    }
1315
1316    //Accumulate acquireFenceFds for MDP Overlays
1317    if(list->outbufAcquireFenceFd >= 0) {
1318        //Writeback output buffer
1319        acquireFd[count++] = list->outbufAcquireFenceFd;
1320    }
1321
1322    for(uint32_t i = 0; i < list->numHwLayers; i++) {
1323        if(list->hwLayers[i].compositionType == HWC_OVERLAY &&
1324                        list->hwLayers[i].acquireFenceFd >= 0) {
1325            if(UNLIKELY(swapzero))
1326                acquireFd[count++] = -1;
1327            else
1328                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
1329        }
1330        if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
1331            if(UNLIKELY(swapzero))
1332                acquireFd[count++] = -1;
1333            else if(fd >= 0) {
1334                //set the acquireFD from fd - which is coming from c2d
1335                acquireFd[count++] = fd;
1336                // Buffer sync IOCTL should be async when using c2d fence is
1337                // used
1338                data.flags &= ~MDP_BUF_SYNC_FLAG_WAIT;
1339            } else if(list->hwLayers[i].acquireFenceFd >= 0)
1340                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
1341        }
1342    }
1343
1344    data.acq_fen_fd_cnt = count;
1345    fbFd = ctx->dpyAttr[dpy].fd;
1346
1347    //Waits for acquire fences, returns a release fence
1348    if(LIKELY(!swapzero)) {
1349        uint64_t start = systemTime();
1350        ret = ioctl(fbFd, MSMFB_BUFFER_SYNC, &data);
1351        ALOGD_IF(HWC_UTILS_DEBUG, "%s: time taken for MSMFB_BUFFER_SYNC IOCTL = %d",
1352                            __FUNCTION__, (size_t) ns2ms(systemTime() - start));
1353    }
1354
1355    if(ret < 0) {
1356        ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed, err=%s",
1357                  __FUNCTION__, strerror(errno));
1358        ALOGE("%s: acq_fen_fd_cnt=%d flags=%d fd=%d dpy=%d numHwLayers=%zu",
1359              __FUNCTION__, data.acq_fen_fd_cnt, data.flags, fbFd,
1360              dpy, list->numHwLayers);
1361    }
1362
1363    for(uint32_t i = 0; i < list->numHwLayers; i++) {
1364        if(list->hwLayers[i].compositionType == HWC_OVERLAY ||
1365#ifdef QCOM_BSP
1366           list->hwLayers[i].compositionType == HWC_BLIT ||
1367#endif
1368           list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
1369            //Populate releaseFenceFds.
1370            if(UNLIKELY(swapzero)) {
1371                list->hwLayers[i].releaseFenceFd = -1;
1372            } else if(isExtAnimating) {
1373                // Release all the app layer fds immediately,
1374                // if animation is in progress.
1375                list->hwLayers[i].releaseFenceFd = -1;
1376            } else if(list->hwLayers[i].releaseFenceFd < 0 ) {
1377#ifdef QCOM_BSP
1378                //If rotator has not already populated this field
1379                if(list->hwLayers[i].compositionType == HWC_BLIT) {
1380                    //For Blit, the app layers should be released when the Blit is
1381                    //complete. This fd was passed from copybit->draw
1382                    list->hwLayers[i].releaseFenceFd = dup(fd);
1383                } else
1384#endif
1385                {
1386                    list->hwLayers[i].releaseFenceFd = dup(releaseFd);
1387                }
1388            }
1389        }
1390    }
1391
1392    if(fd >= 0) {
1393        close(fd);
1394        fd = -1;
1395    }
1396
1397    if (ctx->mCopyBit[dpy])
1398        ctx->mCopyBit[dpy]->setReleaseFd(releaseFd);
1399
1400    //Signals when MDP finishes reading rotator buffers.
1401    ctx->mLayerRotMap[dpy]->setReleaseFd(releaseFd);
1402    close(releaseFd);
1403    releaseFd = -1;
1404
1405    if(UNLIKELY(swapzero)) {
1406        list->retireFenceFd = -1;
1407    } else {
1408        list->retireFenceFd = retireFd;
1409    }
1410    return ret;
1411}
1412
1413void setMdpFlags(hwc_layer_1_t *layer,
1414        ovutils::eMdpFlags &mdpFlags,
1415        int rotDownscale, int transform) {
1416    private_handle_t *hnd = (private_handle_t *)layer->handle;
1417    MetaData_t *metadata = hnd ? (MetaData_t *)hnd->base_metadata : NULL;
1418
1419    if(layer->blending == HWC_BLENDING_PREMULT) {
1420        ovutils::setMdpFlags(mdpFlags,
1421                ovutils::OV_MDP_BLEND_FG_PREMULT);
1422    }
1423
1424    if(isYuvBuffer(hnd)) {
1425        if(isSecureBuffer(hnd)) {
1426            ovutils::setMdpFlags(mdpFlags,
1427                    ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
1428        }
1429        if(metadata && (metadata->operation & PP_PARAM_INTERLACED) &&
1430                metadata->interlaced) {
1431            ovutils::setMdpFlags(mdpFlags,
1432                    ovutils::OV_MDP_DEINTERLACE);
1433        }
1434        //Pre-rotation will be used using rotator.
1435        if(transform & HWC_TRANSFORM_ROT_90) {
1436            ovutils::setMdpFlags(mdpFlags,
1437                    ovutils::OV_MDP_SOURCE_ROTATED_90);
1438        }
1439    }
1440
1441    if(isSecureDisplayBuffer(hnd)) {
1442        // Secure display needs both SECURE_OVERLAY and SECURE_DISPLAY_OV
1443        ovutils::setMdpFlags(mdpFlags,
1444                             ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
1445        ovutils::setMdpFlags(mdpFlags,
1446                             ovutils::OV_MDP_SECURE_DISPLAY_OVERLAY_SESSION);
1447    }
1448    //No 90 component and no rot-downscale then flips done by MDP
1449    //If we use rot then it might as well do flips
1450    if(!(transform & HWC_TRANSFORM_ROT_90) && !rotDownscale) {
1451        if(transform & HWC_TRANSFORM_FLIP_H) {
1452            ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_FLIP_H);
1453        }
1454
1455        if(transform & HWC_TRANSFORM_FLIP_V) {
1456            ovutils::setMdpFlags(mdpFlags,  ovutils::OV_MDP_FLIP_V);
1457        }
1458    }
1459
1460    if(metadata &&
1461        ((metadata->operation & PP_PARAM_HSIC)
1462        || (metadata->operation & PP_PARAM_IGC)
1463        || (metadata->operation & PP_PARAM_SHARP2))) {
1464        ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_PP_EN);
1465    }
1466}
1467
1468int configRotator(Rotator *rot, Whf& whf,
1469        hwc_rect_t& crop, const eMdpFlags& mdpFlags,
1470        const eTransform& orient, const int& downscale) {
1471
1472    // Fix alignments for TILED format
1473    if(whf.format == MDP_Y_CRCB_H2V2_TILE ||
1474                            whf.format == MDP_Y_CBCR_H2V2_TILE) {
1475        whf.w =  utils::alignup(whf.w, 64);
1476        whf.h = utils::alignup(whf.h, 32);
1477    }
1478    rot->setSource(whf);
1479
1480    if (qdutils::MDPVersion::getInstance().getMDPVersion() >=
1481        qdutils::MDSS_V5) {
1482        uint32_t crop_w = (crop.right - crop.left);
1483        uint32_t crop_h = (crop.bottom - crop.top);
1484        if (ovutils::isYuv(whf.format)) {
1485            ovutils::normalizeCrop((uint32_t&)crop.left, crop_w);
1486            ovutils::normalizeCrop((uint32_t&)crop.top, crop_h);
1487            // For interlaced, crop.h should be 4-aligned
1488            if ((mdpFlags & ovutils::OV_MDP_DEINTERLACE) && (crop_h % 4))
1489                crop_h = ovutils::aligndown(crop_h, 4);
1490            crop.right = crop.left + crop_w;
1491            crop.bottom = crop.top + crop_h;
1492        }
1493        Dim rotCrop(crop.left, crop.top, crop_w, crop_h);
1494        rot->setCrop(rotCrop);
1495    }
1496
1497    rot->setFlags(mdpFlags);
1498    rot->setTransform(orient);
1499    rot->setDownscale(downscale);
1500    if(!rot->commit()) return -1;
1501    return 0;
1502}
1503
1504int configMdp(Overlay *ov, const PipeArgs& parg,
1505        const eTransform& orient, const hwc_rect_t& crop,
1506        const hwc_rect_t& pos, const MetaData_t *metadata,
1507        const eDest& dest) {
1508    ov->setSource(parg, dest);
1509    ov->setTransform(orient, dest);
1510
1511    int crop_w = crop.right - crop.left;
1512    int crop_h = crop.bottom - crop.top;
1513    Dim dcrop(crop.left, crop.top, crop_w, crop_h);
1514    ov->setCrop(dcrop, dest);
1515
1516    int posW = pos.right - pos.left;
1517    int posH = pos.bottom - pos.top;
1518    Dim position(pos.left, pos.top, posW, posH);
1519    ov->setPosition(position, dest);
1520
1521    if (metadata)
1522        ov->setVisualParams(*metadata, dest);
1523
1524    if (!ov->commit(dest)) {
1525        return -1;
1526    }
1527    return 0;
1528}
1529
1530int configColorLayer(hwc_context_t *ctx, hwc_layer_1_t *layer,
1531        const int& dpy, eMdpFlags& mdpFlags, eZorder& z,
1532        eIsFg& isFg, const eDest& dest) {
1533
1534    hwc_rect_t dst = layer->displayFrame;
1535    trimLayer(ctx, dpy, 0, dst, dst);
1536
1537    int w = ctx->dpyAttr[dpy].xres;
1538    int h = ctx->dpyAttr[dpy].yres;
1539    int dst_w = dst.right - dst.left;
1540    int dst_h = dst.bottom - dst.top;
1541    uint32_t color = layer->transform;
1542    Whf whf(w, h, getMdpFormat(HAL_PIXEL_FORMAT_RGBA_8888), 0);
1543
1544    ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_SOLID_FILL);
1545    if (layer->blending == HWC_BLENDING_PREMULT)
1546        ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_BLEND_FG_PREMULT);
1547
1548    PipeArgs parg(mdpFlags, whf, z, isFg, static_cast<eRotFlags>(0),
1549                  layer->planeAlpha,
1550                  (ovutils::eBlending) getBlending(layer->blending));
1551
1552    // Configure MDP pipe for Color layer
1553    Dim pos(dst.left, dst.top, dst_w, dst_h);
1554    ctx->mOverlay->setSource(parg, dest);
1555    ctx->mOverlay->setColor(color, dest);
1556    ctx->mOverlay->setTransform(0, dest);
1557    ctx->mOverlay->setCrop(pos, dest);
1558    ctx->mOverlay->setPosition(pos, dest);
1559
1560    if (!ctx->mOverlay->commit(dest)) {
1561        ALOGE("%s: Configure color layer failed!", __FUNCTION__);
1562        return -1;
1563    }
1564    return 0;
1565}
1566
1567void updateSource(eTransform& orient, Whf& whf,
1568        hwc_rect_t& crop) {
1569    Dim srcCrop(crop.left, crop.top,
1570            crop.right - crop.left,
1571            crop.bottom - crop.top);
1572    orient = static_cast<eTransform>(ovutils::getMdpOrient(orient));
1573    preRotateSource(orient, whf, srcCrop);
1574    if (qdutils::MDPVersion::getInstance().getMDPVersion() >=
1575        qdutils::MDSS_V5) {
1576        // Source for overlay will be the cropped (and rotated)
1577        crop.left = 0;
1578        crop.top = 0;
1579        crop.right = srcCrop.w;
1580        crop.bottom = srcCrop.h;
1581        // Set width & height equal to sourceCrop w & h
1582        whf.w = srcCrop.w;
1583        whf.h = srcCrop.h;
1584    } else {
1585        crop.left = srcCrop.x;
1586        crop.top = srcCrop.y;
1587        crop.right = srcCrop.x + srcCrop.w;
1588        crop.bottom = srcCrop.y + srcCrop.h;
1589    }
1590}
1591
1592int configureNonSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
1593        const int& dpy, eMdpFlags& mdpFlags, eZorder& z,
1594        eIsFg& isFg, const eDest& dest, Rotator **rot) {
1595
1596    private_handle_t *hnd = (private_handle_t *)layer->handle;
1597
1598    if(!hnd) {
1599        if (layer->flags & HWC_COLOR_FILL) {
1600            // Configure Color layer
1601            return configColorLayer(ctx, layer, dpy, mdpFlags, z, isFg, dest);
1602        }
1603        ALOGE("%s: layer handle is NULL", __FUNCTION__);
1604        return -1;
1605    }
1606
1607    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
1608
1609    hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
1610    hwc_rect_t dst = layer->displayFrame;
1611    int transform = layer->transform;
1612    eTransform orient = static_cast<eTransform>(transform);
1613    int downscale = 0;
1614    int rotFlags = ovutils::ROT_FLAGS_NONE;
1615    uint32_t format = ovutils::getMdpFormat(hnd->format, isTileRendered(hnd));
1616    Whf whf(getWidth(hnd), getHeight(hnd), format, (uint32_t)hnd->size);
1617
1618    // Handle R/B swap
1619    if (layer->flags & HWC_FORMAT_RB_SWAP) {
1620        if (hnd->format == HAL_PIXEL_FORMAT_RGBA_8888)
1621            whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRA_8888);
1622        else if (hnd->format == HAL_PIXEL_FORMAT_RGBX_8888)
1623            whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRX_8888);
1624    }
1625
1626    calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient);
1627
1628    if(isYuvBuffer(hnd) && ctx->mMDP.version >= qdutils::MDP_V4_2 &&
1629       ctx->mMDP.version < qdutils::MDSS_V5) {
1630        downscale =  getDownscaleFactor(
1631            crop.right - crop.left,
1632            crop.bottom - crop.top,
1633            dst.right - dst.left,
1634            dst.bottom - dst.top);
1635        if(downscale) {
1636            rotFlags = ROT_DOWNSCALE_ENABLED;
1637        }
1638    }
1639
1640    setMdpFlags(layer, mdpFlags, downscale, transform);
1641
1642    if(isYuvBuffer(hnd) && //if 90 component or downscale, use rot
1643            ((transform & HWC_TRANSFORM_ROT_90) || downscale)) {
1644        *rot = ctx->mRotMgr->getNext();
1645        if(*rot == NULL) return -1;
1646        ctx->mLayerRotMap[dpy]->add(layer, *rot);
1647        if(!dpy)
1648            BwcPM::setBwc(crop, dst, transform, mdpFlags);
1649        //Configure rotator for pre-rotation
1650        if(configRotator(*rot, whf, crop, mdpFlags, orient, downscale) < 0) {
1651            ALOGE("%s: configRotator failed!", __FUNCTION__);
1652            return -1;
1653        }
1654        whf.format = (*rot)->getDstFormat();
1655        updateSource(orient, whf, crop);
1656        rotFlags |= ovutils::ROT_PREROTATED;
1657    }
1658
1659    //For the mdp, since either we are pre-rotating or MDP does flips
1660    orient = OVERLAY_TRANSFORM_0;
1661    transform = 0;
1662    PipeArgs parg(mdpFlags, whf, z, isFg,
1663                  static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
1664                  (ovutils::eBlending) getBlending(layer->blending));
1665
1666    if(configMdp(ctx->mOverlay, parg, orient, crop, dst, metadata, dest) < 0) {
1667        ALOGE("%s: commit failed for low res panel", __FUNCTION__);
1668        return -1;
1669    }
1670    return 0;
1671}
1672
1673//Helper to 1) Ensure crops dont have gaps 2) Ensure L and W are even
1674void sanitizeSourceCrop(hwc_rect_t& cropL, hwc_rect_t& cropR,
1675        private_handle_t *hnd) {
1676    if(cropL.right - cropL.left) {
1677        if(isYuvBuffer(hnd)) {
1678            //Always safe to even down left
1679            ovutils::even_floor(cropL.left);
1680            //If right is even, automatically width is even, since left is
1681            //already even
1682            ovutils::even_floor(cropL.right);
1683        }
1684        //Make sure there are no gaps between left and right splits if the layer
1685        //is spread across BOTH halves
1686        if(cropR.right - cropR.left) {
1687            cropR.left = cropL.right;
1688        }
1689    }
1690
1691    if(cropR.right - cropR.left) {
1692        if(isYuvBuffer(hnd)) {
1693            //Always safe to even down left
1694            ovutils::even_floor(cropR.left);
1695            //If right is even, automatically width is even, since left is
1696            //already even
1697            ovutils::even_floor(cropR.right);
1698        }
1699    }
1700}
1701
1702int configureSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
1703        const int& dpy, eMdpFlags& mdpFlagsL, eZorder& z,
1704        eIsFg& isFg, const eDest& lDest, const eDest& rDest,
1705        Rotator **rot) {
1706    private_handle_t *hnd = (private_handle_t *)layer->handle;
1707    if(!hnd) {
1708        ALOGE("%s: layer handle is NULL", __FUNCTION__);
1709        return -1;
1710    }
1711
1712    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
1713
1714    int hw_w = ctx->dpyAttr[dpy].xres;
1715    int hw_h = ctx->dpyAttr[dpy].yres;
1716    hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
1717    hwc_rect_t dst = layer->displayFrame;
1718    int transform = layer->transform;
1719    eTransform orient = static_cast<eTransform>(transform);
1720    const int downscale = 0;
1721    int rotFlags = ROT_FLAGS_NONE;
1722    uint32_t format = ovutils::getMdpFormat(hnd->format, isTileRendered(hnd));
1723    Whf whf(getWidth(hnd), getHeight(hnd), format, (uint32_t)hnd->size);
1724
1725    // Handle R/B swap
1726    if (layer->flags & HWC_FORMAT_RB_SWAP) {
1727        if (hnd->format == HAL_PIXEL_FORMAT_RGBA_8888)
1728            whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRA_8888);
1729        else if (hnd->format == HAL_PIXEL_FORMAT_RGBX_8888)
1730            whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRX_8888);
1731    }
1732
1733    /* Calculate the external display position based on MDP downscale,
1734       ActionSafe, and extorientation features. */
1735    calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient);
1736
1737    setMdpFlags(layer, mdpFlagsL, 0, transform);
1738
1739    if(lDest != OV_INVALID && rDest != OV_INVALID) {
1740        //Enable overfetch
1741        setMdpFlags(mdpFlagsL, OV_MDSS_MDP_DUAL_PIPE);
1742    }
1743
1744    //Will do something only if feature enabled and conditions suitable
1745    //hollow call otherwise
1746    if(ctx->mAD->prepare(ctx, crop, whf, hnd)) {
1747        overlay::Writeback *wb = overlay::Writeback::getInstance();
1748        whf.format = wb->getOutputFormat();
1749    }
1750
1751    if(isYuvBuffer(hnd) && (transform & HWC_TRANSFORM_ROT_90)) {
1752        (*rot) = ctx->mRotMgr->getNext();
1753        if((*rot) == NULL) return -1;
1754        ctx->mLayerRotMap[dpy]->add(layer, *rot);
1755        //Configure rotator for pre-rotation
1756        if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale) < 0) {
1757            ALOGE("%s: configRotator failed!", __FUNCTION__);
1758            return -1;
1759        }
1760        whf.format = (*rot)->getDstFormat();
1761        updateSource(orient, whf, crop);
1762        rotFlags |= ROT_PREROTATED;
1763    }
1764
1765    eMdpFlags mdpFlagsR = mdpFlagsL;
1766    setMdpFlags(mdpFlagsR, OV_MDSS_MDP_RIGHT_MIXER);
1767
1768    hwc_rect_t tmp_cropL = {0}, tmp_dstL = {0};
1769    hwc_rect_t tmp_cropR = {0}, tmp_dstR = {0};
1770
1771    const int lSplit = getLeftSplit(ctx, dpy);
1772
1773    if(lDest != OV_INVALID) {
1774        tmp_cropL = crop;
1775        tmp_dstL = dst;
1776        hwc_rect_t scissor = {0, 0, lSplit, hw_h };
1777        scissor = getIntersection(ctx->mViewFrame[dpy], scissor);
1778        qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
1779    }
1780    if(rDest != OV_INVALID) {
1781        tmp_cropR = crop;
1782        tmp_dstR = dst;
1783        hwc_rect_t scissor = {lSplit, 0, hw_w, hw_h };
1784        scissor = getIntersection(ctx->mViewFrame[dpy], scissor);
1785        qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
1786    }
1787
1788    sanitizeSourceCrop(tmp_cropL, tmp_cropR, hnd);
1789
1790    //When buffer is H-flipped, contents of mixer config also needs to swapped
1791    //Not needed if the layer is confined to one half of the screen.
1792    //If rotator has been used then it has also done the flips, so ignore them.
1793    if((orient & OVERLAY_TRANSFORM_FLIP_H) && lDest != OV_INVALID
1794            && rDest != OV_INVALID && (*rot) == NULL) {
1795        hwc_rect_t new_cropR;
1796        new_cropR.left = tmp_cropL.left;
1797        new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
1798
1799        hwc_rect_t new_cropL;
1800        new_cropL.left  = new_cropR.right;
1801        new_cropL.right = tmp_cropR.right;
1802
1803        tmp_cropL.left =  new_cropL.left;
1804        tmp_cropL.right =  new_cropL.right;
1805
1806        tmp_cropR.left = new_cropR.left;
1807        tmp_cropR.right =  new_cropR.right;
1808
1809    }
1810
1811    //For the mdp, since either we are pre-rotating or MDP does flips
1812    orient = OVERLAY_TRANSFORM_0;
1813    transform = 0;
1814
1815    //configure left mixer
1816    if(lDest != OV_INVALID) {
1817        PipeArgs pargL(mdpFlagsL, whf, z, isFg,
1818                       static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
1819                       (ovutils::eBlending) getBlending(layer->blending));
1820
1821        if(configMdp(ctx->mOverlay, pargL, orient,
1822                tmp_cropL, tmp_dstL, metadata, lDest) < 0) {
1823            ALOGE("%s: commit failed for left mixer config", __FUNCTION__);
1824            return -1;
1825        }
1826    }
1827
1828    //configure right mixer
1829    if(rDest != OV_INVALID) {
1830        PipeArgs pargR(mdpFlagsR, whf, z, isFg,
1831                       static_cast<eRotFlags>(rotFlags),
1832                       layer->planeAlpha,
1833                       (ovutils::eBlending) getBlending(layer->blending));
1834        tmp_dstR.right = tmp_dstR.right - lSplit;
1835        tmp_dstR.left = tmp_dstR.left - lSplit;
1836        if(configMdp(ctx->mOverlay, pargR, orient,
1837                tmp_cropR, tmp_dstR, metadata, rDest) < 0) {
1838            ALOGE("%s: commit failed for right mixer config", __FUNCTION__);
1839            return -1;
1840        }
1841    }
1842
1843    return 0;
1844}
1845
1846int configureSourceSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
1847        const int& dpy, eMdpFlags& mdpFlagsL, eZorder& z,
1848        eIsFg& isFg, const eDest& lDest, const eDest& rDest,
1849        Rotator **rot) {
1850    private_handle_t *hnd = (private_handle_t *)layer->handle;
1851    if(!hnd) {
1852        ALOGE("%s: layer handle is NULL", __FUNCTION__);
1853        return -1;
1854    }
1855
1856    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
1857
1858    hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);;
1859    hwc_rect_t dst = layer->displayFrame;
1860    int transform = layer->transform;
1861    eTransform orient = static_cast<eTransform>(transform);
1862    const int downscale = 0;
1863    int rotFlags = ROT_FLAGS_NONE;
1864    //Splitting only YUV layer on primary panel needs different zorders
1865    //for both layers as both the layers are configured to single mixer
1866    eZorder lz = z;
1867    eZorder rz = (eZorder)(z + 1);
1868
1869    Whf whf(getWidth(hnd), getHeight(hnd),
1870            getMdpFormat(hnd->format), (uint32_t)hnd->size);
1871
1872    /* Calculate the external display position based on MDP downscale,
1873       ActionSafe, and extorientation features. */
1874    calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient);
1875
1876    setMdpFlags(layer, mdpFlagsL, 0, transform);
1877    trimLayer(ctx, dpy, transform, crop, dst);
1878
1879    if(isYuvBuffer(hnd) && (transform & HWC_TRANSFORM_ROT_90)) {
1880        (*rot) = ctx->mRotMgr->getNext();
1881        if((*rot) == NULL) return -1;
1882        ctx->mLayerRotMap[dpy]->add(layer, *rot);
1883        if(!dpy)
1884            BwcPM::setBwc(crop, dst, transform, mdpFlagsL);
1885        //Configure rotator for pre-rotation
1886        if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale) < 0) {
1887            ALOGE("%s: configRotator failed!", __FUNCTION__);
1888            return -1;
1889        }
1890        whf.format = (*rot)->getDstFormat();
1891        updateSource(orient, whf, crop);
1892        rotFlags |= ROT_PREROTATED;
1893    }
1894
1895    eMdpFlags mdpFlagsR = mdpFlagsL;
1896    int lSplit = dst.left + (dst.right - dst.left)/2;
1897
1898    hwc_rect_t tmp_cropL = {0}, tmp_dstL = {0};
1899    hwc_rect_t tmp_cropR = {0}, tmp_dstR = {0};
1900
1901    if(lDest != OV_INVALID) {
1902        tmp_cropL = crop;
1903        tmp_dstL = dst;
1904        hwc_rect_t scissor = {dst.left, dst.top, lSplit, dst.bottom };
1905        qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
1906    }
1907    if(rDest != OV_INVALID) {
1908        tmp_cropR = crop;
1909        tmp_dstR = dst;
1910        hwc_rect_t scissor = {lSplit, dst.top, dst.right, dst.bottom };
1911        qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
1912    }
1913
1914    sanitizeSourceCrop(tmp_cropL, tmp_cropR, hnd);
1915
1916    //When buffer is H-flipped, contents of mixer config also needs to swapped
1917    //Not needed if the layer is confined to one half of the screen.
1918    //If rotator has been used then it has also done the flips, so ignore them.
1919    if((orient & OVERLAY_TRANSFORM_FLIP_H) && lDest != OV_INVALID
1920            && rDest != OV_INVALID && (*rot) == NULL) {
1921        hwc_rect_t new_cropR;
1922        new_cropR.left = tmp_cropL.left;
1923        new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
1924
1925        hwc_rect_t new_cropL;
1926        new_cropL.left  = new_cropR.right;
1927        new_cropL.right = tmp_cropR.right;
1928
1929        tmp_cropL.left =  new_cropL.left;
1930        tmp_cropL.right =  new_cropL.right;
1931
1932        tmp_cropR.left = new_cropR.left;
1933        tmp_cropR.right =  new_cropR.right;
1934
1935    }
1936
1937    //For the mdp, since either we are pre-rotating or MDP does flips
1938    orient = OVERLAY_TRANSFORM_0;
1939    transform = 0;
1940
1941    //configure left half
1942    if(lDest != OV_INVALID) {
1943        PipeArgs pargL(mdpFlagsL, whf, lz, isFg,
1944                static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
1945                (ovutils::eBlending) getBlending(layer->blending));
1946
1947        if(configMdp(ctx->mOverlay, pargL, orient,
1948                    tmp_cropL, tmp_dstL, metadata, lDest) < 0) {
1949            ALOGE("%s: commit failed for left half config", __FUNCTION__);
1950            return -1;
1951        }
1952    }
1953
1954    //configure right half
1955    if(rDest != OV_INVALID) {
1956        PipeArgs pargR(mdpFlagsR, whf, rz, isFg,
1957                static_cast<eRotFlags>(rotFlags),
1958                layer->planeAlpha,
1959                (ovutils::eBlending) getBlending(layer->blending));
1960        if(configMdp(ctx->mOverlay, pargR, orient,
1961                    tmp_cropR, tmp_dstR, metadata, rDest) < 0) {
1962            ALOGE("%s: commit failed for right half config", __FUNCTION__);
1963            return -1;
1964        }
1965    }
1966
1967    return 0;
1968}
1969
1970bool canUseRotator(hwc_context_t *ctx, int dpy) {
1971    if(ctx->mOverlay->isDMAMultiplexingSupported() &&
1972            isSecondaryConnected(ctx) &&
1973            !ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].isPause) {
1974        /* mdss driver on certain targets support multiplexing of DMA pipe
1975         * in LINE and BLOCK modes for writeback panels.
1976         */
1977        if(dpy == HWC_DISPLAY_PRIMARY)
1978            return false;
1979    }
1980    if(ctx->mMDP.version == qdutils::MDP_V3_0_4)
1981        return false;
1982    return true;
1983}
1984
1985int getLeftSplit(hwc_context_t *ctx, const int& dpy) {
1986    //Default even split for all displays with high res
1987    int lSplit = ctx->dpyAttr[dpy].xres / 2;
1988    if(dpy == HWC_DISPLAY_PRIMARY &&
1989            qdutils::MDPVersion::getInstance().getLeftSplit()) {
1990        //Override if split published by driver for primary
1991        lSplit = qdutils::MDPVersion::getInstance().getLeftSplit();
1992    }
1993    return lSplit;
1994}
1995
1996bool isDisplaySplit(hwc_context_t* ctx, int dpy) {
1997    if(ctx->dpyAttr[dpy].xres > qdutils::MAX_DISPLAY_DIM) {
1998        return true;
1999    }
2000    //For testing we could split primary via device tree values
2001    if(dpy == HWC_DISPLAY_PRIMARY &&
2002        qdutils::MDPVersion::getInstance().getRightSplit()) {
2003        return true;
2004    }
2005    return false;
2006}
2007
2008//clear prev layer prop flags and realloc for current frame
2009void reset_layer_prop(hwc_context_t* ctx, int dpy, int numAppLayers) {
2010    if(ctx->layerProp[dpy]) {
2011       delete[] ctx->layerProp[dpy];
2012       ctx->layerProp[dpy] = NULL;
2013    }
2014    ctx->layerProp[dpy] = new LayerProp[numAppLayers];
2015}
2016
2017/* Since we fake non-Hybrid WFD solution as external display, this
2018 * function helps us in determining the priority between external
2019 * (hdmi/non-Hybrid WFD display) and virtual display devices(SSD/
2020 * screenrecord). This can be removed once wfd-client migrates to
2021 * using virtual-display api's.
2022 */
2023bool canUseMDPforVirtualDisplay(hwc_context_t* ctx,
2024                                const hwc_display_contents_1_t *list) {
2025
2026    /* We rely on the fact that for pure virtual display solution
2027     * list->outbuf will be a non-NULL handle.
2028     *
2029     * If there are three active displays (which means there is one
2030     * primary, one external and one virtual active display)
2031     * we give mdss/mdp hw resources(pipes,smp,etc) for external
2032     * display(hdmi/non-Hybrid WFD display) rather than for virtual
2033     * display(SSD/screenrecord)
2034     */
2035
2036    if(list->outbuf and (ctx->numActiveDisplays == HWC_NUM_DISPLAY_TYPES)) {
2037        return false;
2038    }
2039
2040    return true;
2041}
2042
2043bool isGLESComp(hwc_context_t *ctx,
2044                     hwc_display_contents_1_t* list) {
2045    int numAppLayers = ctx->listStats[HWC_DISPLAY_PRIMARY].numAppLayers;
2046    for(int index = 0; index < numAppLayers; index++) {
2047        hwc_layer_1_t* layer = &(list->hwLayers[index]);
2048        if(layer->compositionType == HWC_FRAMEBUFFER)
2049            return true;
2050    }
2051    return false;
2052}
2053
2054void setGPUHint(hwc_context_t* ctx, hwc_display_contents_1_t* list) {
2055    struct gpu_hint_info *gpuHint = &ctx->mGPUHintInfo;
2056    if(!gpuHint->mGpuPerfModeEnable || !ctx || !list)
2057        return;
2058
2059#ifdef QCOM_BSP
2060    /* Set the GPU hint flag to high for MIXED/GPU composition only for
2061       first frame after MDP -> GPU/MIXED mode transition. Set the GPU
2062       hint to default if the previous composition is GPU or current GPU
2063       composition is due to idle fallback */
2064    if(!gpuHint->mEGLDisplay || !gpuHint->mEGLContext) {
2065        gpuHint->mEGLDisplay = eglGetCurrentDisplay();
2066        if(!gpuHint->mEGLDisplay) {
2067            ALOGW("%s Warning: EGL current display is NULL", __FUNCTION__);
2068            return;
2069        }
2070        gpuHint->mEGLContext = eglGetCurrentContext();
2071        if(!gpuHint->mEGLContext) {
2072            ALOGW("%s Warning: EGL current context is NULL", __FUNCTION__);
2073            return;
2074        }
2075    }
2076    if(isGLESComp(ctx, list)) {
2077        if(!gpuHint->mPrevCompositionGLES && !MDPComp::isIdleFallback()) {
2078            EGLint attr_list[] = {EGL_GPU_HINT_1,
2079                                  EGL_GPU_LEVEL_3,
2080                                  EGL_NONE };
2081            if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_3) &&
2082                !eglGpuPerfHintQCOM(gpuHint->mEGLDisplay,
2083                                    gpuHint->mEGLContext, attr_list)) {
2084                ALOGW("eglGpuPerfHintQCOM failed for Built in display");
2085            } else {
2086                gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_3;
2087                gpuHint->mPrevCompositionGLES = true;
2088            }
2089        } else {
2090            EGLint attr_list[] = {EGL_GPU_HINT_1,
2091                                  EGL_GPU_LEVEL_0,
2092                                  EGL_NONE };
2093            if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_0) &&
2094                !eglGpuPerfHintQCOM(gpuHint->mEGLDisplay,
2095                                    gpuHint->mEGLContext, attr_list)) {
2096                ALOGW("eglGpuPerfHintQCOM failed for Built in display");
2097            } else {
2098                gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_0;
2099            }
2100        }
2101    } else {
2102        /* set the GPU hint flag to default for MDP composition */
2103        EGLint attr_list[] = {EGL_GPU_HINT_1,
2104                              EGL_GPU_LEVEL_0,
2105                              EGL_NONE };
2106        if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_0) &&
2107                !eglGpuPerfHintQCOM(gpuHint->mEGLDisplay,
2108                                    gpuHint->mEGLContext, attr_list)) {
2109            ALOGW("eglGpuPerfHintQCOM failed for Built in display");
2110        } else {
2111            gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_0;
2112        }
2113        gpuHint->mPrevCompositionGLES = false;
2114    }
2115#endif
2116}
2117
2118void BwcPM::setBwc(const hwc_rect_t& crop,
2119            const hwc_rect_t& dst, const int& transform,
2120            ovutils::eMdpFlags& mdpFlags) {
2121    //Target doesnt support Bwc
2122    if(!qdutils::MDPVersion::getInstance().supportsBWC()) {
2123        return;
2124    }
2125    //src width > MAX mixer supported dim
2126    if((crop.right - crop.left) > qdutils::MAX_DISPLAY_DIM) {
2127        return;
2128    }
2129    //Decimation necessary, cannot use BWC. H/W requirement.
2130    if(qdutils::MDPVersion::getInstance().supportsDecimation()) {
2131        int src_w = crop.right - crop.left;
2132        int src_h = crop.bottom - crop.top;
2133        int dst_w = dst.right - dst.left;
2134        int dst_h = dst.bottom - dst.top;
2135        if(transform & HAL_TRANSFORM_ROT_90) {
2136            swap(src_w, src_h);
2137        }
2138        float horDscale = 0.0f;
2139        float verDscale = 0.0f;
2140        int horzDeci = 0;
2141        int vertDeci = 0;
2142        ovutils::getDecimationFactor(src_w, src_h, dst_w, dst_h, horDscale,
2143                verDscale);
2144        //TODO Use log2f once math.h has it
2145        if((int)horDscale)
2146            horzDeci = (int)(log(horDscale) / log(2));
2147        if((int)verDscale)
2148            vertDeci = (int)(log(verDscale) / log(2));
2149        if(horzDeci || vertDeci) return;
2150    }
2151    //Property
2152    char value[PROPERTY_VALUE_MAX];
2153    property_get("debug.disable.bwc", value, "0");
2154     if(atoi(value)) return;
2155
2156    ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDSS_MDP_BWC_EN);
2157}
2158
2159void LayerRotMap::add(hwc_layer_1_t* layer, Rotator *rot) {
2160    if(mCount >= MAX_SESS) return;
2161    mLayer[mCount] = layer;
2162    mRot[mCount] = rot;
2163    mCount++;
2164}
2165
2166void LayerRotMap::reset() {
2167    for (int i = 0; i < MAX_SESS; i++) {
2168        mLayer[i] = 0;
2169        mRot[i] = 0;
2170    }
2171    mCount = 0;
2172}
2173
2174void LayerRotMap::clear() {
2175    RotMgr::getInstance()->markUnusedTop(mCount);
2176    reset();
2177}
2178
2179void LayerRotMap::setReleaseFd(const int& fence) {
2180    for(uint32_t i = 0; i < mCount; i++) {
2181        mRot[i]->setReleaseFd(dup(fence));
2182    }
2183}
2184
2185void resetROI(hwc_context_t *ctx, const int dpy) {
2186    const int fbXRes = (int)ctx->dpyAttr[dpy].xres;
2187    const int fbYRes = (int)ctx->dpyAttr[dpy].yres;
2188    if(isDisplaySplit(ctx, dpy)) {
2189        const int lSplit = getLeftSplit(ctx, dpy);
2190        ctx->listStats[dpy].lRoi = (struct hwc_rect){0, 0, lSplit, fbYRes};
2191        ctx->listStats[dpy].rRoi = (struct hwc_rect){lSplit, 0, fbXRes, fbYRes};
2192    } else  {
2193        ctx->listStats[dpy].lRoi = (struct hwc_rect){0, 0,fbXRes, fbYRes};
2194        ctx->listStats[dpy].rRoi = (struct hwc_rect){0, 0, 0, 0};
2195    }
2196}
2197
2198hwc_rect_t getSanitizeROI(struct hwc_rect roi, hwc_rect boundary)
2199{
2200   if(!isValidRect(roi))
2201      return roi;
2202
2203   struct hwc_rect t_roi = roi;
2204
2205   const int LEFT_ALIGN = qdutils::MDPVersion::getInstance().getLeftAlign();
2206   const int WIDTH_ALIGN = qdutils::MDPVersion::getInstance().getWidthAlign();
2207   const int TOP_ALIGN = qdutils::MDPVersion::getInstance().getTopAlign();
2208   const int HEIGHT_ALIGN = qdutils::MDPVersion::getInstance().getHeightAlign();
2209   const int MIN_WIDTH = qdutils::MDPVersion::getInstance().getMinROIWidth();
2210   const int MIN_HEIGHT = qdutils::MDPVersion::getInstance().getMinROIHeight();
2211
2212   /* Align to minimum width recommended by the panel */
2213   if((t_roi.right - t_roi.left) < MIN_WIDTH) {
2214       if((t_roi.left + MIN_WIDTH) > boundary.right)
2215           t_roi.left = t_roi.right - MIN_WIDTH;
2216       else
2217           t_roi.right = t_roi.left + MIN_WIDTH;
2218   }
2219
2220  /* Align to minimum height recommended by the panel */
2221   if((t_roi.bottom - t_roi.top) < MIN_HEIGHT) {
2222       if((t_roi.top + MIN_HEIGHT) > boundary.bottom)
2223           t_roi.top = t_roi.bottom - MIN_HEIGHT;
2224       else
2225           t_roi.bottom = t_roi.top + MIN_HEIGHT;
2226   }
2227
2228   /* Align left and width to meet panel restrictions */
2229   if(LEFT_ALIGN)
2230       t_roi.left = t_roi.left - (t_roi.left % LEFT_ALIGN);
2231
2232   if(WIDTH_ALIGN) {
2233       int width = t_roi.right - t_roi.left;
2234       width = WIDTH_ALIGN * ((width + (WIDTH_ALIGN - 1)) / WIDTH_ALIGN);
2235       t_roi.right = t_roi.left + width;
2236
2237       if(t_roi.right > boundary.right) {
2238           t_roi.right = boundary.right;
2239           t_roi.left = t_roi.right - width;
2240
2241           if(LEFT_ALIGN)
2242               t_roi.left = t_roi.left - (t_roi.left % LEFT_ALIGN);
2243       }
2244   }
2245
2246
2247   /* Align top and height to meet panel restrictions */
2248   if(TOP_ALIGN)
2249       t_roi.top = t_roi.top - (t_roi.top % TOP_ALIGN);
2250
2251   if(HEIGHT_ALIGN) {
2252       int height = t_roi.bottom - t_roi.top;
2253       height = HEIGHT_ALIGN *  ((height + (HEIGHT_ALIGN - 1)) / HEIGHT_ALIGN);
2254       t_roi.bottom = t_roi.top  + height;
2255
2256       if(t_roi.bottom > boundary.bottom) {
2257           t_roi.bottom = boundary.bottom;
2258           t_roi.top = t_roi.bottom - height;
2259
2260           if(TOP_ALIGN)
2261               t_roi.top = t_roi.top - (t_roi.top % TOP_ALIGN);
2262       }
2263   }
2264
2265
2266   return t_roi;
2267}
2268
2269};//namespace qhwc
2270