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