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