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