hwc_utils.cpp revision 8636d6ec09a6886169903d2f4de259fac8bfcdfd
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)((float)inPos.x/actualWidth);
485    yRatio = (float)((float)inPos.y/actualHeight);
486    wRatio = (float)((float)inPos.w/actualWidth);
487    hRatio = (float)((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
811void setListStats(hwc_context_t *ctx,
812        hwc_display_contents_1_t *list, int dpy) {
813    const int prevYuvCount = ctx->listStats[dpy].yuvCount;
814    memset(&ctx->listStats[dpy], 0, sizeof(ListStats));
815    ctx->listStats[dpy].numAppLayers = (int)list->numHwLayers - 1;
816    ctx->listStats[dpy].fbLayerIndex = (int)list->numHwLayers - 1;
817    ctx->listStats[dpy].skipCount = 0;
818    ctx->listStats[dpy].preMultipliedAlpha = false;
819    ctx->listStats[dpy].isSecurePresent = false;
820    ctx->listStats[dpy].yuvCount = 0;
821    char property[PROPERTY_VALUE_MAX];
822    ctx->listStats[dpy].extOnlyLayerIndex = -1;
823    ctx->listStats[dpy].isDisplayAnimating = false;
824    ctx->listStats[dpy].secureUI = false;
825    ctx->listStats[dpy].yuv4k2kCount = 0;
826    ctx->dpyAttr[dpy].mActionSafePresent = isActionSafePresent(ctx, dpy);
827    ctx->listStats[dpy].renderBufIndexforABC = -1;
828
829    resetROI(ctx, dpy);
830
831    trimList(ctx, list, dpy);
832    optimizeLayerRects(list);
833    for (size_t i = 0; i < (size_t)ctx->listStats[dpy].numAppLayers; i++) {
834        hwc_layer_1_t const* layer = &list->hwLayers[i];
835        private_handle_t *hnd = (private_handle_t *)layer->handle;
836
837#ifdef QCOM_BSP
838        if (layer->flags & HWC_SCREENSHOT_ANIMATOR_LAYER) {
839            ctx->listStats[dpy].isDisplayAnimating = true;
840        }
841        if(isSecureDisplayBuffer(hnd)) {
842            ctx->listStats[dpy].secureUI = true;
843        }
844#endif
845        // continue if number of app layers exceeds MAX_NUM_APP_LAYERS
846        if(ctx->listStats[dpy].numAppLayers > MAX_NUM_APP_LAYERS)
847            continue;
848
849        //reset yuv indices
850        ctx->listStats[dpy].yuvIndices[i] = -1;
851        ctx->listStats[dpy].yuv4k2kIndices[i] = -1;
852
853        if (isSecureBuffer(hnd)) {
854            ctx->listStats[dpy].isSecurePresent = true;
855        }
856
857        if (isSkipLayer(&list->hwLayers[i])) {
858            ctx->listStats[dpy].skipCount++;
859        }
860
861        if (UNLIKELY(isYuvBuffer(hnd))) {
862            int& yuvCount = ctx->listStats[dpy].yuvCount;
863            ctx->listStats[dpy].yuvIndices[yuvCount] = (int)i;
864            yuvCount++;
865
866            if(UNLIKELY(is4kx2kYuvBuffer(hnd))){
867                int& yuv4k2kCount = ctx->listStats[dpy].yuv4k2kCount;
868                ctx->listStats[dpy].yuv4k2kIndices[yuv4k2kCount] = (int)i;
869                yuv4k2kCount++;
870            }
871        }
872        if(layer->blending == HWC_BLENDING_PREMULT)
873            ctx->listStats[dpy].preMultipliedAlpha = true;
874
875
876        if(UNLIKELY(isExtOnly(hnd))){
877            ctx->listStats[dpy].extOnlyLayerIndex = (int)i;
878        }
879    }
880    if(ctx->listStats[dpy].yuvCount > 0) {
881        if (property_get("hw.cabl.yuv", property, NULL) > 0) {
882            if (atoi(property) != 1) {
883                property_set("hw.cabl.yuv", "1");
884            }
885        }
886    } else {
887        if (property_get("hw.cabl.yuv", property, NULL) > 0) {
888            if (atoi(property) != 0) {
889                property_set("hw.cabl.yuv", "0");
890            }
891        }
892    }
893
894    //The marking of video begin/end is useful on some targets where we need
895    //to have a padding round to be able to shift pipes across mixers.
896    if(prevYuvCount != ctx->listStats[dpy].yuvCount) {
897        ctx->mVideoTransFlag = true;
898    }
899
900    if(dpy == HWC_DISPLAY_PRIMARY) {
901        ctx->mAD->markDoable(ctx, list);
902    }
903}
904
905
906static void calc_cut(double& leftCutRatio, double& topCutRatio,
907        double& rightCutRatio, double& bottomCutRatio, int orient) {
908    if(orient & HAL_TRANSFORM_FLIP_H) {
909        swap(leftCutRatio, rightCutRatio);
910    }
911    if(orient & HAL_TRANSFORM_FLIP_V) {
912        swap(topCutRatio, bottomCutRatio);
913    }
914    if(orient & HAL_TRANSFORM_ROT_90) {
915        //Anti clock swapping
916        double tmpCutRatio = leftCutRatio;
917        leftCutRatio = topCutRatio;
918        topCutRatio = rightCutRatio;
919        rightCutRatio = bottomCutRatio;
920        bottomCutRatio = tmpCutRatio;
921    }
922}
923
924bool isSecuring(hwc_context_t* ctx, hwc_layer_1_t const* layer) {
925    if((ctx->mMDP.version < qdutils::MDSS_V5) &&
926       (ctx->mMDP.version > qdutils::MDP_V3_0) &&
927        ctx->mSecuring) {
928        return true;
929    }
930    if (isSecureModePolicy(ctx->mMDP.version)) {
931        private_handle_t *hnd = (private_handle_t *)layer->handle;
932        if(ctx->mSecureMode) {
933            if (! isSecureBuffer(hnd)) {
934                ALOGD_IF(HWC_UTILS_DEBUG,"%s:Securing Turning ON ...",
935                         __FUNCTION__);
936                return true;
937            }
938        } else {
939            if (isSecureBuffer(hnd)) {
940                ALOGD_IF(HWC_UTILS_DEBUG,"%s:Securing Turning OFF ...",
941                         __FUNCTION__);
942                return true;
943            }
944        }
945    }
946    return false;
947}
948
949bool isSecureModePolicy(int mdpVersion) {
950    if (mdpVersion < qdutils::MDSS_V5)
951        return true;
952    else
953        return false;
954}
955
956bool isRotatorSupportedFormat(private_handle_t *hnd) {
957    // Following rotator src formats are supported by mdp driver
958    // TODO: Add more formats in future, if mdp driver adds support
959    switch(hnd->format) {
960        case HAL_PIXEL_FORMAT_RGBA_8888:
961        case HAL_PIXEL_FORMAT_RGB_565:
962        case HAL_PIXEL_FORMAT_RGB_888:
963        case HAL_PIXEL_FORMAT_BGRA_8888:
964            return true;
965        default:
966            return false;
967    }
968    return false;
969}
970
971bool isRotationDoable(hwc_context_t *ctx, private_handle_t *hnd) {
972    // Rotate layers, if it is YUV type or rendered by CPU and not
973    // for the MDP versions below MDP5
974    if((isCPURendered(hnd) && isRotatorSupportedFormat(hnd) &&
975        !ctx->mMDP.version < qdutils::MDSS_V5)
976                   || isYuvBuffer(hnd)) {
977        return true;
978    }
979    return false;
980}
981
982// returns true if Action safe dimensions are set and target supports Actionsafe
983bool isActionSafePresent(hwc_context_t *ctx, int dpy) {
984    // if external supports underscan, do nothing
985    // it will be taken care in the driver
986    // Disable Action safe for 8974 due to HW limitation for downscaling
987    // layers with overlapped region
988    // Disable Actionsafe for non HDMI displays.
989    if(!(dpy == HWC_DISPLAY_EXTERNAL) ||
990        qdutils::MDPVersion::getInstance().is8x74v2() ||
991        ctx->mExtDisplay->isCEUnderscanSupported()) {
992        return false;
993    }
994
995    char value[PROPERTY_VALUE_MAX];
996    // Read action safe properties
997    property_get("persist.sys.actionsafe.width", value, "0");
998    ctx->dpyAttr[dpy].mAsWidthRatio = atoi(value);
999    property_get("persist.sys.actionsafe.height", value, "0");
1000    ctx->dpyAttr[dpy].mAsHeightRatio = atoi(value);
1001
1002    if(!ctx->dpyAttr[dpy].mAsWidthRatio && !ctx->dpyAttr[dpy].mAsHeightRatio) {
1003        //No action safe ratio set, return
1004        return false;
1005    }
1006    return true;
1007}
1008
1009int getBlending(int blending) {
1010    switch(blending) {
1011    case HWC_BLENDING_NONE:
1012        return overlay::utils::OVERLAY_BLENDING_OPAQUE;
1013    case HWC_BLENDING_PREMULT:
1014        return overlay::utils::OVERLAY_BLENDING_PREMULT;
1015    case HWC_BLENDING_COVERAGE :
1016    default:
1017        return overlay::utils::OVERLAY_BLENDING_COVERAGE;
1018    }
1019}
1020
1021//Crops source buffer against destination and FB boundaries
1022void calculate_crop_rects(hwc_rect_t& crop, hwc_rect_t& dst,
1023                          const hwc_rect_t& scissor, int orient) {
1024
1025    int& crop_l = crop.left;
1026    int& crop_t = crop.top;
1027    int& crop_r = crop.right;
1028    int& crop_b = crop.bottom;
1029    int crop_w = crop.right - crop.left;
1030    int crop_h = crop.bottom - crop.top;
1031
1032    int& dst_l = dst.left;
1033    int& dst_t = dst.top;
1034    int& dst_r = dst.right;
1035    int& dst_b = dst.bottom;
1036    int dst_w = abs(dst.right - dst.left);
1037    int dst_h = abs(dst.bottom - dst.top);
1038
1039    const int& sci_l = scissor.left;
1040    const int& sci_t = scissor.top;
1041    const int& sci_r = scissor.right;
1042    const int& sci_b = scissor.bottom;
1043
1044    double leftCutRatio = 0.0, rightCutRatio = 0.0, topCutRatio = 0.0,
1045            bottomCutRatio = 0.0;
1046
1047    if(dst_l < sci_l) {
1048        leftCutRatio = (double)(sci_l - dst_l) / (double)dst_w;
1049        dst_l = sci_l;
1050    }
1051
1052    if(dst_r > sci_r) {
1053        rightCutRatio = (double)(dst_r - sci_r) / (double)dst_w;
1054        dst_r = sci_r;
1055    }
1056
1057    if(dst_t < sci_t) {
1058        topCutRatio = (double)(sci_t - dst_t) / (double)dst_h;
1059        dst_t = sci_t;
1060    }
1061
1062    if(dst_b > sci_b) {
1063        bottomCutRatio = (double)(dst_b - sci_b) / (double)dst_h;
1064        dst_b = sci_b;
1065    }
1066
1067    calc_cut(leftCutRatio, topCutRatio, rightCutRatio, bottomCutRatio, orient);
1068    crop_l += (int)round((double)crop_w * leftCutRatio);
1069    crop_t += (int)round((double)crop_h * topCutRatio);
1070    crop_r -= (int)round((double)crop_w * rightCutRatio);
1071    crop_b -= (int)round((double)crop_h * bottomCutRatio);
1072}
1073
1074bool areLayersIntersecting(const hwc_layer_1_t* layer1,
1075        const hwc_layer_1_t* layer2) {
1076    hwc_rect_t irect = getIntersection(layer1->displayFrame,
1077            layer2->displayFrame);
1078    return isValidRect(irect);
1079}
1080
1081bool isSameRect(const hwc_rect& rect1, const hwc_rect& rect2)
1082{
1083   return ((rect1.left == rect2.left) && (rect1.top == rect2.top) &&
1084           (rect1.right == rect2.right) && (rect1.bottom == rect2.bottom));
1085}
1086
1087bool isValidRect(const hwc_rect& rect)
1088{
1089   return ((rect.bottom > rect.top) && (rect.right > rect.left)) ;
1090}
1091
1092bool operator ==(const hwc_rect_t& lhs, const hwc_rect_t& rhs) {
1093    if(lhs.left == rhs.left && lhs.top == rhs.top &&
1094       lhs.right == rhs.right &&  lhs.bottom == rhs.bottom )
1095          return true ;
1096    return false;
1097}
1098
1099hwc_rect_t moveRect(const hwc_rect_t& rect, const int& x_off, const int& y_off)
1100{
1101    hwc_rect_t res;
1102
1103    if(!isValidRect(rect))
1104        return (hwc_rect_t){0, 0, 0, 0};
1105
1106    res.left = rect.left + x_off;
1107    res.top = rect.top + y_off;
1108    res.right = rect.right + x_off;
1109    res.bottom = rect.bottom + y_off;
1110
1111    return res;
1112}
1113
1114/* computes the intersection of two rects */
1115hwc_rect_t getIntersection(const hwc_rect_t& rect1, const hwc_rect_t& rect2)
1116{
1117   hwc_rect_t res;
1118
1119   if(!isValidRect(rect1) || !isValidRect(rect2)){
1120      return (hwc_rect_t){0, 0, 0, 0};
1121   }
1122
1123
1124   res.left = max(rect1.left, rect2.left);
1125   res.top = max(rect1.top, rect2.top);
1126   res.right = min(rect1.right, rect2.right);
1127   res.bottom = min(rect1.bottom, rect2.bottom);
1128
1129   if(!isValidRect(res))
1130      return (hwc_rect_t){0, 0, 0, 0};
1131
1132   return res;
1133}
1134
1135/* computes the union of two rects */
1136hwc_rect_t getUnion(const hwc_rect &rect1, const hwc_rect &rect2)
1137{
1138   hwc_rect_t res;
1139
1140   if(!isValidRect(rect1)){
1141      return rect2;
1142   }
1143
1144   if(!isValidRect(rect2)){
1145      return rect1;
1146   }
1147
1148   res.left = min(rect1.left, rect2.left);
1149   res.top = min(rect1.top, rect2.top);
1150   res.right =  max(rect1.right, rect2.right);
1151   res.bottom =  max(rect1.bottom, rect2.bottom);
1152
1153   return res;
1154}
1155
1156/* Not a geometrical rect deduction. Deducts rect2 from rect1 only if it results
1157 * a single rect */
1158hwc_rect_t deductRect(const hwc_rect_t& rect1, const hwc_rect_t& rect2) {
1159
1160   hwc_rect_t res = rect1;
1161
1162   if((rect1.left == rect2.left) && (rect1.right == rect2.right)) {
1163      if((rect1.top == rect2.top) && (rect2.bottom <= rect1.bottom))
1164         res.top = rect2.bottom;
1165      else if((rect1.bottom == rect2.bottom)&& (rect2.top >= rect1.top))
1166         res.bottom = rect2.top;
1167   }
1168   else if((rect1.top == rect2.top) && (rect1.bottom == rect2.bottom)) {
1169      if((rect1.left == rect2.left) && (rect2.right <= rect1.right))
1170         res.left = rect2.right;
1171      else if((rect1.right == rect2.right)&& (rect2.left >= rect1.left))
1172         res.right = rect2.left;
1173   }
1174   return res;
1175}
1176
1177void optimizeLayerRects(const hwc_display_contents_1_t *list) {
1178    int i= (int)list->numHwLayers-2;
1179    while(i > 0) {
1180        //see if there is no blending required.
1181        //If it is opaque see if we can substract this region from below
1182        //layers.
1183        if(list->hwLayers[i].blending == HWC_BLENDING_NONE) {
1184            int j= i-1;
1185            hwc_rect_t& topframe =
1186                (hwc_rect_t&)list->hwLayers[i].displayFrame;
1187            while(j >= 0) {
1188               if(!needsScaling(&list->hwLayers[j])) {
1189                  hwc_layer_1_t* layer = (hwc_layer_1_t*)&list->hwLayers[j];
1190                  hwc_rect_t& bottomframe = layer->displayFrame;
1191                  hwc_rect_t bottomCrop =
1192                      integerizeSourceCrop(layer->sourceCropf);
1193                  int transform =layer->transform;
1194
1195                  hwc_rect_t irect = getIntersection(bottomframe, topframe);
1196                  if(isValidRect(irect)) {
1197                     hwc_rect_t dest_rect;
1198                     //if intersection is valid rect, deduct it
1199                     dest_rect  = deductRect(bottomframe, irect);
1200                     qhwc::calculate_crop_rects(bottomCrop, bottomframe,
1201                                                dest_rect, transform);
1202                     //Update layer sourceCropf
1203                     layer->sourceCropf.left =(float)bottomCrop.left;
1204                     layer->sourceCropf.top = (float)bottomCrop.top;
1205                     layer->sourceCropf.right = (float)bottomCrop.right;
1206                     layer->sourceCropf.bottom = (float)bottomCrop.bottom;
1207#ifdef QCOM_BSP
1208                     //Update layer dirtyRect
1209                     layer->dirtyRect = getIntersection(bottomCrop,
1210                                            layer->dirtyRect);
1211#endif
1212                  }
1213               }
1214               j--;
1215            }
1216        }
1217        i--;
1218    }
1219}
1220
1221void getNonWormholeRegion(hwc_display_contents_1_t* list,
1222                              hwc_rect_t& nwr)
1223{
1224    size_t last = list->numHwLayers - 1;
1225    hwc_rect_t fbDisplayFrame = list->hwLayers[last].displayFrame;
1226    //Initiliaze nwr to first frame
1227    nwr.left =  list->hwLayers[0].displayFrame.left;
1228    nwr.top =  list->hwLayers[0].displayFrame.top;
1229    nwr.right =  list->hwLayers[0].displayFrame.right;
1230    nwr.bottom =  list->hwLayers[0].displayFrame.bottom;
1231
1232    for (size_t i = 1; i < last; i++) {
1233        hwc_rect_t displayFrame = list->hwLayers[i].displayFrame;
1234        nwr = getUnion(nwr, displayFrame);
1235    }
1236
1237    //Intersect with the framebuffer
1238    nwr = getIntersection(nwr, fbDisplayFrame);
1239}
1240
1241bool isExternalActive(hwc_context_t* ctx) {
1242    return ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].isActive;
1243}
1244
1245void closeAcquireFds(hwc_display_contents_1_t* list) {
1246    if(LIKELY(list)) {
1247        for(uint32_t i = 0; i < list->numHwLayers; i++) {
1248            //Close the acquireFenceFds
1249            //HWC_FRAMEBUFFER are -1 already by SF, rest we close.
1250            if(list->hwLayers[i].acquireFenceFd >= 0) {
1251                close(list->hwLayers[i].acquireFenceFd);
1252                list->hwLayers[i].acquireFenceFd = -1;
1253            }
1254        }
1255        //Writeback
1256        if(list->outbufAcquireFenceFd >= 0) {
1257            close(list->outbufAcquireFenceFd);
1258            list->outbufAcquireFenceFd = -1;
1259        }
1260    }
1261}
1262
1263int hwc_sync(hwc_context_t *ctx, hwc_display_contents_1_t* list, int dpy,
1264        int fd) {
1265    ATRACE_CALL();
1266    int ret = 0;
1267    int acquireFd[MAX_NUM_APP_LAYERS];
1268    int count = 0;
1269    int releaseFd = -1;
1270    int retireFd = -1;
1271    int fbFd = -1;
1272    bool swapzero = false;
1273
1274    struct mdp_buf_sync data;
1275    memset(&data, 0, sizeof(data));
1276    data.acq_fen_fd = acquireFd;
1277    data.rel_fen_fd = &releaseFd;
1278    data.retire_fen_fd = &retireFd;
1279    data.flags = MDP_BUF_SYNC_FLAG_RETIRE_FENCE;
1280
1281    char property[PROPERTY_VALUE_MAX];
1282    if(property_get("debug.egl.swapinterval", property, "1") > 0) {
1283        if(atoi(property) == 0)
1284            swapzero = true;
1285    }
1286
1287    bool isExtAnimating = false;
1288    if(dpy)
1289       isExtAnimating = ctx->listStats[dpy].isDisplayAnimating;
1290
1291    //Send acquireFenceFds to rotator
1292    for(uint32_t i = 0; i < ctx->mLayerRotMap[dpy]->getCount(); i++) {
1293        int rotFd = ctx->mRotMgr->getRotDevFd();
1294        int rotReleaseFd = -1;
1295        overlay::Rotator* currRot = ctx->mLayerRotMap[dpy]->getRot(i);
1296        hwc_layer_1_t* currLayer = ctx->mLayerRotMap[dpy]->getLayer(i);
1297        if((currRot == NULL) || (currLayer == NULL)) {
1298            continue;
1299        }
1300        struct mdp_buf_sync rotData;
1301        memset(&rotData, 0, sizeof(rotData));
1302        rotData.acq_fen_fd =
1303                &currLayer->acquireFenceFd;
1304        rotData.rel_fen_fd = &rotReleaseFd; //driver to populate this
1305        rotData.session_id = currRot->getSessId();
1306        if(currLayer->acquireFenceFd >= 0) {
1307            rotData.acq_fen_fd_cnt = 1; //1 ioctl call per rot session
1308        }
1309        int ret = 0;
1310        ret = ioctl(rotFd, MSMFB_BUFFER_SYNC, &rotData);
1311        if(ret < 0) {
1312            ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed for rot sync, err=%s",
1313                    __FUNCTION__, strerror(errno));
1314            close(rotReleaseFd);
1315        } else {
1316            close(currLayer->acquireFenceFd);
1317            //For MDP to wait on.
1318            currLayer->acquireFenceFd =
1319                    dup(rotReleaseFd);
1320            //A buffer is free to be used by producer as soon as its copied to
1321            //rotator
1322            currLayer->releaseFenceFd =
1323                    rotReleaseFd;
1324        }
1325    }
1326
1327    //Accumulate acquireFenceFds for MDP Overlays
1328    if(list->outbufAcquireFenceFd >= 0) {
1329        //Writeback output buffer
1330        acquireFd[count++] = list->outbufAcquireFenceFd;
1331    }
1332
1333    for(uint32_t i = 0; i < list->numHwLayers; i++) {
1334        if(((isAbcInUse(ctx)== true ) ||
1335          (list->hwLayers[i].compositionType == HWC_OVERLAY)) &&
1336                        list->hwLayers[i].acquireFenceFd >= 0) {
1337            if(UNLIKELY(swapzero))
1338                acquireFd[count++] = -1;
1339            // if ABC is enabled for more than one layer.
1340            // renderBufIndexforABC will work as FB.Hence
1341            // set the acquireFD from fd - which is coming from copybit
1342            else if(fd >= 0 && (isAbcInUse(ctx) == true)) {
1343                if(ctx->listStats[dpy].renderBufIndexforABC ==(int32_t)i)
1344                   acquireFd[count++] = fd;
1345                else
1346                   continue;
1347            } else
1348                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
1349        }
1350        if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
1351            if(UNLIKELY(swapzero))
1352                acquireFd[count++] = -1;
1353            else if(fd >= 0) {
1354                //set the acquireFD from fd - which is coming from c2d
1355                acquireFd[count++] = fd;
1356                // Buffer sync IOCTL should be async when using c2d fence is
1357                // used
1358                data.flags &= ~MDP_BUF_SYNC_FLAG_WAIT;
1359            } else if(list->hwLayers[i].acquireFenceFd >= 0)
1360                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
1361        }
1362    }
1363
1364    if ((fd >= 0) && !dpy && ctx->mMDPComp[dpy]->isPTORActive()) {
1365        // Acquire c2d fence of Overlap render buffer
1366        acquireFd[count++] = fd;
1367    }
1368
1369    data.acq_fen_fd_cnt = count;
1370    fbFd = ctx->dpyAttr[dpy].fd;
1371
1372    //Waits for acquire fences, returns a release fence
1373    if(LIKELY(!swapzero)) {
1374        ret = ioctl(fbFd, MSMFB_BUFFER_SYNC, &data);
1375    }
1376
1377    if(ret < 0) {
1378        ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed, err=%s",
1379                  __FUNCTION__, strerror(errno));
1380        ALOGE("%s: acq_fen_fd_cnt=%d flags=%d fd=%d dpy=%d numHwLayers=%zu",
1381              __FUNCTION__, data.acq_fen_fd_cnt, data.flags, fbFd,
1382              dpy, list->numHwLayers);
1383        close(releaseFd);
1384        releaseFd = -1;
1385        close(retireFd);
1386        retireFd = -1;
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_context_t *ctx, 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    }
1472
1473    if(isSecureDisplayBuffer(hnd)) {
1474        // Secure display needs both SECURE_OVERLAY and SECURE_DISPLAY_OV
1475        ovutils::setMdpFlags(mdpFlags,
1476                             ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
1477        ovutils::setMdpFlags(mdpFlags,
1478                             ovutils::OV_MDP_SECURE_DISPLAY_OVERLAY_SESSION);
1479    }
1480
1481    //Pre-rotation will be used using rotator.
1482    if(has90Transform(layer) && isRotationDoable(ctx, hnd)) {
1483        ovutils::setMdpFlags(mdpFlags,
1484                ovutils::OV_MDP_SOURCE_ROTATED_90);
1485    }
1486    //No 90 component and no rot-downscale then flips done by MDP
1487    //If we use rot then it might as well do flips
1488    if(!(transform & HWC_TRANSFORM_ROT_90) && !rotDownscale) {
1489        if(transform & HWC_TRANSFORM_FLIP_H) {
1490            ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_FLIP_H);
1491        }
1492
1493        if(transform & HWC_TRANSFORM_FLIP_V) {
1494            ovutils::setMdpFlags(mdpFlags,  ovutils::OV_MDP_FLIP_V);
1495        }
1496    }
1497
1498    if(metadata &&
1499        ((metadata->operation & PP_PARAM_HSIC)
1500        || (metadata->operation & PP_PARAM_IGC)
1501        || (metadata->operation & PP_PARAM_SHARP2))) {
1502        ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_PP_EN);
1503    }
1504}
1505
1506int configRotator(Rotator *rot, Whf& whf,
1507        hwc_rect_t& crop, const eMdpFlags& mdpFlags,
1508        const eTransform& orient, const int& downscale) {
1509
1510    // Fix alignments for TILED format
1511    if(whf.format == MDP_Y_CRCB_H2V2_TILE ||
1512                            whf.format == MDP_Y_CBCR_H2V2_TILE) {
1513        whf.w =  utils::alignup(whf.w, 64);
1514        whf.h = utils::alignup(whf.h, 32);
1515    }
1516    rot->setSource(whf);
1517
1518    if (qdutils::MDPVersion::getInstance().getMDPVersion() >=
1519        qdutils::MDSS_V5) {
1520        uint32_t crop_w = (crop.right - crop.left);
1521        uint32_t crop_h = (crop.bottom - crop.top);
1522        if (ovutils::isYuv(whf.format)) {
1523            ovutils::normalizeCrop((uint32_t&)crop.left, crop_w);
1524            ovutils::normalizeCrop((uint32_t&)crop.top, crop_h);
1525            // For interlaced, crop.h should be 4-aligned
1526            if ((mdpFlags & ovutils::OV_MDP_DEINTERLACE) && (crop_h % 4))
1527                crop_h = ovutils::aligndown(crop_h, 4);
1528            crop.right = crop.left + crop_w;
1529            crop.bottom = crop.top + crop_h;
1530        }
1531        Dim rotCrop(crop.left, crop.top, crop_w, crop_h);
1532        rot->setCrop(rotCrop);
1533    }
1534
1535    rot->setFlags(mdpFlags);
1536    rot->setTransform(orient);
1537    rot->setDownscale(downscale);
1538    if(!rot->commit()) return -1;
1539    return 0;
1540}
1541
1542int configMdp(Overlay *ov, const PipeArgs& parg,
1543        const eTransform& orient, const hwc_rect_t& crop,
1544        const hwc_rect_t& pos, const MetaData_t *metadata,
1545        const eDest& dest) {
1546    ov->setSource(parg, dest);
1547    ov->setTransform(orient, dest);
1548
1549    int crop_w = crop.right - crop.left;
1550    int crop_h = crop.bottom - crop.top;
1551    Dim dcrop(crop.left, crop.top, crop_w, crop_h);
1552    ov->setCrop(dcrop, dest);
1553
1554    int posW = pos.right - pos.left;
1555    int posH = pos.bottom - pos.top;
1556    Dim position(pos.left, pos.top, posW, posH);
1557    ov->setPosition(position, dest);
1558
1559    if (metadata)
1560        ov->setVisualParams(*metadata, dest);
1561
1562    if (!ov->commit(dest)) {
1563        return -1;
1564    }
1565    return 0;
1566}
1567
1568int configColorLayer(hwc_context_t *ctx, hwc_layer_1_t *layer,
1569        const int& dpy, eMdpFlags& mdpFlags, eZorder& z,
1570        eIsFg& isFg, const eDest& dest) {
1571
1572    hwc_rect_t dst = layer->displayFrame;
1573    trimLayer(ctx, dpy, 0, dst, dst);
1574
1575    int w = ctx->dpyAttr[dpy].xres;
1576    int h = ctx->dpyAttr[dpy].yres;
1577    int dst_w = dst.right - dst.left;
1578    int dst_h = dst.bottom - dst.top;
1579    uint32_t color = layer->transform;
1580    Whf whf(w, h, getMdpFormat(HAL_PIXEL_FORMAT_RGBA_8888), 0);
1581
1582    ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_SOLID_FILL);
1583    if (layer->blending == HWC_BLENDING_PREMULT)
1584        ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_BLEND_FG_PREMULT);
1585
1586    PipeArgs parg(mdpFlags, whf, z, isFg, static_cast<eRotFlags>(0),
1587                  layer->planeAlpha,
1588                  (ovutils::eBlending) getBlending(layer->blending));
1589
1590    // Configure MDP pipe for Color layer
1591    Dim pos(dst.left, dst.top, dst_w, dst_h);
1592    ctx->mOverlay->setSource(parg, dest);
1593    ctx->mOverlay->setColor(color, dest);
1594    ctx->mOverlay->setTransform(0, dest);
1595    ctx->mOverlay->setCrop(pos, dest);
1596    ctx->mOverlay->setPosition(pos, dest);
1597
1598    if (!ctx->mOverlay->commit(dest)) {
1599        ALOGE("%s: Configure color layer failed!", __FUNCTION__);
1600        return -1;
1601    }
1602    return 0;
1603}
1604
1605void updateSource(eTransform& orient, Whf& whf,
1606        hwc_rect_t& crop) {
1607    Dim srcCrop(crop.left, crop.top,
1608            crop.right - crop.left,
1609            crop.bottom - crop.top);
1610    orient = static_cast<eTransform>(ovutils::getMdpOrient(orient));
1611    preRotateSource(orient, whf, srcCrop);
1612    if (qdutils::MDPVersion::getInstance().getMDPVersion() >=
1613        qdutils::MDSS_V5) {
1614        // Source for overlay will be the cropped (and rotated)
1615        crop.left = 0;
1616        crop.top = 0;
1617        crop.right = srcCrop.w;
1618        crop.bottom = srcCrop.h;
1619        // Set width & height equal to sourceCrop w & h
1620        whf.w = srcCrop.w;
1621        whf.h = srcCrop.h;
1622    } else {
1623        crop.left = srcCrop.x;
1624        crop.top = srcCrop.y;
1625        crop.right = srcCrop.x + srcCrop.w;
1626        crop.bottom = srcCrop.y + srcCrop.h;
1627    }
1628}
1629
1630int configureNonSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
1631        const int& dpy, eMdpFlags& mdpFlags, eZorder& z,
1632        eIsFg& isFg, const eDest& dest, Rotator **rot) {
1633
1634    private_handle_t *hnd = (private_handle_t *)layer->handle;
1635
1636    if(!hnd) {
1637        if (layer->flags & HWC_COLOR_FILL) {
1638            // Configure Color layer
1639            return configColorLayer(ctx, layer, dpy, mdpFlags, z, isFg, dest);
1640        }
1641        ALOGE("%s: layer handle is NULL", __FUNCTION__);
1642        return -1;
1643    }
1644
1645    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
1646
1647    hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
1648    hwc_rect_t dst = layer->displayFrame;
1649    int transform = layer->transform;
1650    eTransform orient = static_cast<eTransform>(transform);
1651    int downscale = 0;
1652    int rotFlags = ovutils::ROT_FLAGS_NONE;
1653    uint32_t format = ovutils::getMdpFormat(hnd->format, isTileRendered(hnd));
1654    Whf whf(getWidth(hnd), getHeight(hnd), format, (uint32_t)hnd->size);
1655
1656    // Handle R/B swap
1657    if (layer->flags & HWC_FORMAT_RB_SWAP) {
1658        if (hnd->format == HAL_PIXEL_FORMAT_RGBA_8888)
1659            whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRA_8888);
1660        else if (hnd->format == HAL_PIXEL_FORMAT_RGBX_8888)
1661            whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRX_8888);
1662    }
1663
1664    calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient);
1665
1666    if(isYuvBuffer(hnd) && ctx->mMDP.version >= qdutils::MDP_V4_2 &&
1667       ctx->mMDP.version < qdutils::MDSS_V5) {
1668        downscale =  getDownscaleFactor(
1669            crop.right - crop.left,
1670            crop.bottom - crop.top,
1671            dst.right - dst.left,
1672            dst.bottom - dst.top);
1673        if(downscale) {
1674            rotFlags = ROT_DOWNSCALE_ENABLED;
1675        }
1676    }
1677
1678    setMdpFlags(ctx, layer, mdpFlags, downscale, transform);
1679
1680    //if 90 component or downscale, use rot
1681    if((has90Transform(layer) && isRotationDoable(ctx, hnd)) || downscale) {
1682        *rot = ctx->mRotMgr->getNext();
1683        if(*rot == NULL) return -1;
1684        ctx->mLayerRotMap[dpy]->add(layer, *rot);
1685        // BWC is not tested for other formats So enable it only for YUV format
1686        if(!dpy && isYuvBuffer(hnd))
1687            BwcPM::setBwc(crop, dst, transform, mdpFlags);
1688        //Configure rotator for pre-rotation
1689        if(configRotator(*rot, whf, crop, mdpFlags, orient, downscale) < 0) {
1690            ALOGE("%s: configRotator failed!", __FUNCTION__);
1691            return -1;
1692        }
1693        whf.format = (*rot)->getDstFormat();
1694        updateSource(orient, whf, crop);
1695        rotFlags |= ovutils::ROT_PREROTATED;
1696    }
1697
1698    //For the mdp, since either we are pre-rotating or MDP does flips
1699    orient = OVERLAY_TRANSFORM_0;
1700    transform = 0;
1701    PipeArgs parg(mdpFlags, whf, z, isFg,
1702                  static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
1703                  (ovutils::eBlending) getBlending(layer->blending));
1704
1705    if(configMdp(ctx->mOverlay, parg, orient, crop, dst, metadata, dest) < 0) {
1706        ALOGE("%s: commit failed for low res panel", __FUNCTION__);
1707        return -1;
1708    }
1709    return 0;
1710}
1711
1712//Helper to 1) Ensure crops dont have gaps 2) Ensure L and W are even
1713void sanitizeSourceCrop(hwc_rect_t& cropL, hwc_rect_t& cropR,
1714        private_handle_t *hnd) {
1715    if(cropL.right - cropL.left) {
1716        if(isYuvBuffer(hnd)) {
1717            //Always safe to even down left
1718            ovutils::even_floor(cropL.left);
1719            //If right is even, automatically width is even, since left is
1720            //already even
1721            ovutils::even_floor(cropL.right);
1722        }
1723        //Make sure there are no gaps between left and right splits if the layer
1724        //is spread across BOTH halves
1725        if(cropR.right - cropR.left) {
1726            cropR.left = cropL.right;
1727        }
1728    }
1729
1730    if(cropR.right - cropR.left) {
1731        if(isYuvBuffer(hnd)) {
1732            //Always safe to even down left
1733            ovutils::even_floor(cropR.left);
1734            //If right is even, automatically width is even, since left is
1735            //already even
1736            ovutils::even_floor(cropR.right);
1737        }
1738    }
1739}
1740
1741int configureSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
1742        const int& dpy, eMdpFlags& mdpFlagsL, eZorder& z,
1743        eIsFg& isFg, const eDest& lDest, const eDest& rDest,
1744        Rotator **rot) {
1745    private_handle_t *hnd = (private_handle_t *)layer->handle;
1746    if(!hnd) {
1747        ALOGE("%s: layer handle is NULL", __FUNCTION__);
1748        return -1;
1749    }
1750
1751    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
1752
1753    int hw_w = ctx->dpyAttr[dpy].xres;
1754    int hw_h = ctx->dpyAttr[dpy].yres;
1755    hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
1756    hwc_rect_t dst = layer->displayFrame;
1757    int transform = layer->transform;
1758    eTransform orient = static_cast<eTransform>(transform);
1759    const int downscale = 0;
1760    int rotFlags = ROT_FLAGS_NONE;
1761    uint32_t format = ovutils::getMdpFormat(hnd->format, isTileRendered(hnd));
1762    Whf whf(getWidth(hnd), getHeight(hnd), format, (uint32_t)hnd->size);
1763
1764    // Handle R/B swap
1765    if (layer->flags & HWC_FORMAT_RB_SWAP) {
1766        if (hnd->format == HAL_PIXEL_FORMAT_RGBA_8888)
1767            whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRA_8888);
1768        else if (hnd->format == HAL_PIXEL_FORMAT_RGBX_8888)
1769            whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRX_8888);
1770    }
1771
1772    /* Calculate the external display position based on MDP downscale,
1773       ActionSafe, and extorientation features. */
1774    calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient);
1775
1776    setMdpFlags(ctx, layer, mdpFlagsL, 0, transform);
1777
1778    if(lDest != OV_INVALID && rDest != OV_INVALID) {
1779        //Enable overfetch
1780        setMdpFlags(mdpFlagsL, OV_MDSS_MDP_DUAL_PIPE);
1781    }
1782
1783    //Will do something only if feature enabled and conditions suitable
1784    //hollow call otherwise
1785    if(ctx->mAD->prepare(ctx, crop, whf, hnd)) {
1786        overlay::Writeback *wb = overlay::Writeback::getInstance();
1787        whf.format = wb->getOutputFormat();
1788    }
1789
1790    if(has90Transform(layer) && isRotationDoable(ctx, hnd)) {
1791        (*rot) = ctx->mRotMgr->getNext();
1792        if((*rot) == NULL) return -1;
1793        ctx->mLayerRotMap[dpy]->add(layer, *rot);
1794        //Configure rotator for pre-rotation
1795        if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale) < 0) {
1796            ALOGE("%s: configRotator failed!", __FUNCTION__);
1797            return -1;
1798        }
1799        whf.format = (*rot)->getDstFormat();
1800        updateSource(orient, whf, crop);
1801        rotFlags |= ROT_PREROTATED;
1802    }
1803
1804    eMdpFlags mdpFlagsR = mdpFlagsL;
1805    setMdpFlags(mdpFlagsR, OV_MDSS_MDP_RIGHT_MIXER);
1806
1807    hwc_rect_t tmp_cropL = {0}, tmp_dstL = {0};
1808    hwc_rect_t tmp_cropR = {0}, tmp_dstR = {0};
1809
1810    const int lSplit = getLeftSplit(ctx, dpy);
1811
1812    // Calculate Left rects
1813    if(dst.left < lSplit) {
1814        tmp_cropL = crop;
1815        tmp_dstL = dst;
1816        hwc_rect_t scissor = {0, 0, lSplit, hw_h };
1817        scissor = getIntersection(ctx->mViewFrame[dpy], scissor);
1818        qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
1819    }
1820
1821    // Calculate Right rects
1822    if(dst.right > lSplit) {
1823        tmp_cropR = crop;
1824        tmp_dstR = dst;
1825        hwc_rect_t scissor = {lSplit, 0, hw_w, hw_h };
1826        scissor = getIntersection(ctx->mViewFrame[dpy], scissor);
1827        qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
1828    }
1829
1830    sanitizeSourceCrop(tmp_cropL, tmp_cropR, hnd);
1831
1832    //When buffer is H-flipped, contents of mixer config also needs to swapped
1833    //Not needed if the layer is confined to one half of the screen.
1834    //If rotator has been used then it has also done the flips, so ignore them.
1835    if((orient & OVERLAY_TRANSFORM_FLIP_H) && (dst.left < lSplit) &&
1836            (dst.right > lSplit) && (*rot) == NULL) {
1837        hwc_rect_t new_cropR;
1838        new_cropR.left = tmp_cropL.left;
1839        new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
1840
1841        hwc_rect_t new_cropL;
1842        new_cropL.left  = new_cropR.right;
1843        new_cropL.right = tmp_cropR.right;
1844
1845        tmp_cropL.left =  new_cropL.left;
1846        tmp_cropL.right =  new_cropL.right;
1847
1848        tmp_cropR.left = new_cropR.left;
1849        tmp_cropR.right =  new_cropR.right;
1850
1851    }
1852
1853    //For the mdp, since either we are pre-rotating or MDP does flips
1854    orient = OVERLAY_TRANSFORM_0;
1855    transform = 0;
1856
1857    //configure left mixer
1858    if(lDest != OV_INVALID) {
1859        PipeArgs pargL(mdpFlagsL, whf, z, isFg,
1860                       static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
1861                       (ovutils::eBlending) getBlending(layer->blending));
1862
1863        if(configMdp(ctx->mOverlay, pargL, orient,
1864                tmp_cropL, tmp_dstL, metadata, lDest) < 0) {
1865            ALOGE("%s: commit failed for left mixer config", __FUNCTION__);
1866            return -1;
1867        }
1868    }
1869
1870    //configure right mixer
1871    if(rDest != OV_INVALID) {
1872        PipeArgs pargR(mdpFlagsR, whf, z, isFg,
1873                       static_cast<eRotFlags>(rotFlags),
1874                       layer->planeAlpha,
1875                       (ovutils::eBlending) getBlending(layer->blending));
1876        tmp_dstR.right = tmp_dstR.right - lSplit;
1877        tmp_dstR.left = tmp_dstR.left - lSplit;
1878        if(configMdp(ctx->mOverlay, pargR, orient,
1879                tmp_cropR, tmp_dstR, metadata, rDest) < 0) {
1880            ALOGE("%s: commit failed for right mixer config", __FUNCTION__);
1881            return -1;
1882        }
1883    }
1884
1885    return 0;
1886}
1887
1888int configureSourceSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
1889        const int& dpy, eMdpFlags& mdpFlagsL, eZorder& z,
1890        eIsFg& isFg, const eDest& lDest, const eDest& rDest,
1891        Rotator **rot) {
1892    private_handle_t *hnd = (private_handle_t *)layer->handle;
1893    if(!hnd) {
1894        ALOGE("%s: layer handle is NULL", __FUNCTION__);
1895        return -1;
1896    }
1897
1898    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
1899
1900    hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);;
1901    hwc_rect_t dst = layer->displayFrame;
1902    int transform = layer->transform;
1903    eTransform orient = static_cast<eTransform>(transform);
1904    const int downscale = 0;
1905    int rotFlags = ROT_FLAGS_NONE;
1906    //Splitting only YUV layer on primary panel needs different zorders
1907    //for both layers as both the layers are configured to single mixer
1908    eZorder lz = z;
1909    eZorder rz = (eZorder)(z + 1);
1910
1911    Whf whf(getWidth(hnd), getHeight(hnd),
1912            getMdpFormat(hnd->format), (uint32_t)hnd->size);
1913
1914    /* Calculate the external display position based on MDP downscale,
1915       ActionSafe, and extorientation features. */
1916    calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient);
1917
1918    setMdpFlags(ctx, layer, mdpFlagsL, 0, transform);
1919    trimLayer(ctx, dpy, transform, crop, dst);
1920
1921    if(has90Transform(layer) && isRotationDoable(ctx, hnd)) {
1922        (*rot) = ctx->mRotMgr->getNext();
1923        if((*rot) == NULL) return -1;
1924        ctx->mLayerRotMap[dpy]->add(layer, *rot);
1925        // BWC is not tested for other formats So enable it only for YUV format
1926        if(!dpy && isYuvBuffer(hnd))
1927            BwcPM::setBwc(crop, dst, transform, mdpFlagsL);
1928        //Configure rotator for pre-rotation
1929        if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale) < 0) {
1930            ALOGE("%s: configRotator failed!", __FUNCTION__);
1931            return -1;
1932        }
1933        whf.format = (*rot)->getDstFormat();
1934        updateSource(orient, whf, crop);
1935        rotFlags |= ROT_PREROTATED;
1936    }
1937
1938    eMdpFlags mdpFlagsR = mdpFlagsL;
1939    int lSplit = dst.left + (dst.right - dst.left)/2;
1940
1941    hwc_rect_t tmp_cropL = {0}, tmp_dstL = {0};
1942    hwc_rect_t tmp_cropR = {0}, tmp_dstR = {0};
1943
1944    if(lDest != OV_INVALID) {
1945        tmp_cropL = crop;
1946        tmp_dstL = dst;
1947        hwc_rect_t scissor = {dst.left, dst.top, lSplit, dst.bottom };
1948        qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
1949    }
1950    if(rDest != OV_INVALID) {
1951        tmp_cropR = crop;
1952        tmp_dstR = dst;
1953        hwc_rect_t scissor = {lSplit, dst.top, dst.right, dst.bottom };
1954        qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
1955    }
1956
1957    sanitizeSourceCrop(tmp_cropL, tmp_cropR, hnd);
1958
1959    //When buffer is H-flipped, contents of mixer config also needs to swapped
1960    //Not needed if the layer is confined to one half of the screen.
1961    //If rotator has been used then it has also done the flips, so ignore them.
1962    if((orient & OVERLAY_TRANSFORM_FLIP_H) && lDest != OV_INVALID
1963            && rDest != OV_INVALID && (*rot) == NULL) {
1964        hwc_rect_t new_cropR;
1965        new_cropR.left = tmp_cropL.left;
1966        new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
1967
1968        hwc_rect_t new_cropL;
1969        new_cropL.left  = new_cropR.right;
1970        new_cropL.right = tmp_cropR.right;
1971
1972        tmp_cropL.left =  new_cropL.left;
1973        tmp_cropL.right =  new_cropL.right;
1974
1975        tmp_cropR.left = new_cropR.left;
1976        tmp_cropR.right =  new_cropR.right;
1977
1978    }
1979
1980    //For the mdp, since either we are pre-rotating or MDP does flips
1981    orient = OVERLAY_TRANSFORM_0;
1982    transform = 0;
1983
1984    //configure left half
1985    if(lDest != OV_INVALID) {
1986        PipeArgs pargL(mdpFlagsL, whf, lz, isFg,
1987                static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
1988                (ovutils::eBlending) getBlending(layer->blending));
1989
1990        if(configMdp(ctx->mOverlay, pargL, orient,
1991                    tmp_cropL, tmp_dstL, metadata, lDest) < 0) {
1992            ALOGE("%s: commit failed for left half config", __FUNCTION__);
1993            return -1;
1994        }
1995    }
1996
1997    //configure right half
1998    if(rDest != OV_INVALID) {
1999        PipeArgs pargR(mdpFlagsR, whf, rz, isFg,
2000                static_cast<eRotFlags>(rotFlags),
2001                layer->planeAlpha,
2002                (ovutils::eBlending) getBlending(layer->blending));
2003        if(configMdp(ctx->mOverlay, pargR, orient,
2004                    tmp_cropR, tmp_dstR, metadata, rDest) < 0) {
2005            ALOGE("%s: commit failed for right half config", __FUNCTION__);
2006            return -1;
2007        }
2008    }
2009
2010    return 0;
2011}
2012
2013bool canUseRotator(hwc_context_t *ctx, int dpy) {
2014    if(ctx->mOverlay->isDMAMultiplexingSupported() &&
2015            isSecondaryConnected(ctx) &&
2016            !ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].isPause) {
2017        /* mdss driver on certain targets support multiplexing of DMA pipe
2018         * in LINE and BLOCK modes for writeback panels.
2019         */
2020        if(dpy == HWC_DISPLAY_PRIMARY)
2021            return false;
2022    }
2023    if(ctx->mMDP.version == qdutils::MDP_V3_0_4)
2024        return false;
2025    return true;
2026}
2027
2028int getLeftSplit(hwc_context_t *ctx, const int& dpy) {
2029    //Default even split for all displays with high res
2030    int lSplit = ctx->dpyAttr[dpy].xres / 2;
2031    if(dpy == HWC_DISPLAY_PRIMARY &&
2032            qdutils::MDPVersion::getInstance().getLeftSplit()) {
2033        //Override if split published by driver for primary
2034        lSplit = qdutils::MDPVersion::getInstance().getLeftSplit();
2035    }
2036    return lSplit;
2037}
2038
2039bool isDisplaySplit(hwc_context_t* ctx, int dpy) {
2040    if(ctx->dpyAttr[dpy].xres > qdutils::MAX_DISPLAY_DIM) {
2041        return true;
2042    }
2043    //For testing we could split primary via device tree values
2044    if(dpy == HWC_DISPLAY_PRIMARY &&
2045        qdutils::MDPVersion::getInstance().getRightSplit()) {
2046        return true;
2047    }
2048    return false;
2049}
2050
2051//clear prev layer prop flags and realloc for current frame
2052void reset_layer_prop(hwc_context_t* ctx, int dpy, int numAppLayers) {
2053    if(ctx->layerProp[dpy]) {
2054       delete[] ctx->layerProp[dpy];
2055       ctx->layerProp[dpy] = NULL;
2056    }
2057    ctx->layerProp[dpy] = new LayerProp[numAppLayers];
2058}
2059
2060bool isAbcInUse(hwc_context_t *ctx){
2061  return (ctx->enableABC && ctx->listStats[0].renderBufIndexforABC == 0);
2062}
2063
2064/* Since we fake non-Hybrid WFD solution as external display, this
2065 * function helps us in determining the priority between external
2066 * (hdmi/non-Hybrid WFD display) and virtual display devices(SSD/
2067 * screenrecord). This can be removed once wfd-client migrates to
2068 * using virtual-display api's.
2069 */
2070bool canUseMDPforVirtualDisplay(hwc_context_t* ctx,
2071                                const hwc_display_contents_1_t *list) {
2072
2073    /* We rely on the fact that for pure virtual display solution
2074     * list->outbuf will be a non-NULL handle.
2075     *
2076     * If there are three active displays (which means there is one
2077     * primary, one external and one virtual active display)
2078     * we give mdss/mdp hw resources(pipes,smp,etc) for external
2079     * display(hdmi/non-Hybrid WFD display) rather than for virtual
2080     * display(SSD/screenrecord)
2081     */
2082
2083    if(list->outbuf and (ctx->numActiveDisplays == HWC_NUM_DISPLAY_TYPES)) {
2084        return false;
2085    }
2086
2087    return true;
2088}
2089
2090void dumpBuffer(private_handle_t *ohnd, char *bufferName) {
2091    if (ohnd != NULL && ohnd->base) {
2092        char dumpFilename[PATH_MAX];
2093        bool bResult = false;
2094        snprintf(dumpFilename, sizeof(dumpFilename), "/data/%s.%s.%dx%d.raw",
2095            bufferName,
2096            overlay::utils::getFormatString(utils::getMdpFormat(ohnd->format)),
2097            getWidth(ohnd), getHeight(ohnd));
2098        FILE* fp = fopen(dumpFilename, "w+");
2099        if (NULL != fp) {
2100            bResult = (bool) fwrite((void*)ohnd->base, ohnd->size, 1, fp);
2101            fclose(fp);
2102        }
2103        ALOGD("Buffer[%s] Dump to %s: %s",
2104        bufferName, dumpFilename, bResult ? "Success" : "Fail");
2105    }
2106}
2107
2108bool isGLESComp(hwc_context_t *ctx,
2109                     hwc_display_contents_1_t* list) {
2110    int numAppLayers = ctx->listStats[HWC_DISPLAY_PRIMARY].numAppLayers;
2111    for(int index = 0; index < numAppLayers; index++) {
2112        hwc_layer_1_t* layer = &(list->hwLayers[index]);
2113        if(layer->compositionType == HWC_FRAMEBUFFER)
2114            return true;
2115    }
2116    return false;
2117}
2118
2119void setGPUHint(hwc_context_t* ctx, hwc_display_contents_1_t* list) {
2120    struct gpu_hint_info *gpuHint = &ctx->mGPUHintInfo;
2121    if(!gpuHint->mGpuPerfModeEnable || !ctx || !list)
2122        return;
2123
2124#ifdef QCOM_BSP
2125    /* Set the GPU hint flag to high for MIXED/GPU composition only for
2126       first frame after MDP -> GPU/MIXED mode transition. Set the GPU
2127       hint to default if the previous composition is GPU or current GPU
2128       composition is due to idle fallback */
2129    if(!gpuHint->mEGLDisplay || !gpuHint->mEGLContext) {
2130        gpuHint->mEGLDisplay = eglGetCurrentDisplay();
2131        if(!gpuHint->mEGLDisplay) {
2132            ALOGW("%s Warning: EGL current display is NULL", __FUNCTION__);
2133            return;
2134        }
2135        gpuHint->mEGLContext = eglGetCurrentContext();
2136        if(!gpuHint->mEGLContext) {
2137            ALOGW("%s Warning: EGL current context is NULL", __FUNCTION__);
2138            return;
2139        }
2140    }
2141    if(isGLESComp(ctx, list)) {
2142        if(gpuHint->mCompositionState != COMPOSITION_STATE_GPU
2143            && !MDPComp::isIdleFallback()) {
2144            EGLint attr_list[] = {EGL_GPU_HINT_1,
2145                                  EGL_GPU_LEVEL_3,
2146                                  EGL_NONE };
2147            if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_3) &&
2148                !eglGpuPerfHintQCOM(gpuHint->mEGLDisplay,
2149                                    gpuHint->mEGLContext, attr_list)) {
2150                ALOGW("eglGpuPerfHintQCOM failed for Built in display");
2151            } else {
2152                gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_3;
2153                gpuHint->mCompositionState = COMPOSITION_STATE_GPU;
2154            }
2155        } else {
2156            EGLint attr_list[] = {EGL_GPU_HINT_1,
2157                                  EGL_GPU_LEVEL_0,
2158                                  EGL_NONE };
2159            if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_0) &&
2160                !eglGpuPerfHintQCOM(gpuHint->mEGLDisplay,
2161                                    gpuHint->mEGLContext, attr_list)) {
2162                ALOGW("eglGpuPerfHintQCOM failed for Built in display");
2163            } else {
2164                gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_0;
2165            }
2166            if(MDPComp::isIdleFallback()) {
2167                gpuHint->mCompositionState = COMPOSITION_STATE_IDLE_FALLBACK;
2168            }
2169        }
2170    } else {
2171        /* set the GPU hint flag to default for MDP composition */
2172        EGLint attr_list[] = {EGL_GPU_HINT_1,
2173                              EGL_GPU_LEVEL_0,
2174                              EGL_NONE };
2175        if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_0) &&
2176                !eglGpuPerfHintQCOM(gpuHint->mEGLDisplay,
2177                                    gpuHint->mEGLContext, attr_list)) {
2178            ALOGW("eglGpuPerfHintQCOM failed for Built in display");
2179        } else {
2180            gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_0;
2181        }
2182        gpuHint->mCompositionState = COMPOSITION_STATE_MDP;
2183    }
2184#endif
2185}
2186
2187bool isPeripheral(const hwc_rect_t& rect1, const hwc_rect_t& rect2) {
2188    // To be peripheral, 3 boundaries should match.
2189    uint8_t eqBounds = 0;
2190    if (rect1.left == rect2.left)
2191        eqBounds++;
2192    if (rect1.top == rect2.top)
2193        eqBounds++;
2194    if (rect1.right == rect2.right)
2195        eqBounds++;
2196    if (rect1.bottom == rect2.bottom)
2197        eqBounds++;
2198    return (eqBounds == 3);
2199}
2200
2201void BwcPM::setBwc(const hwc_rect_t& crop,
2202            const hwc_rect_t& dst, const int& transform,
2203            ovutils::eMdpFlags& mdpFlags) {
2204    //Target doesnt support Bwc
2205    if(!qdutils::MDPVersion::getInstance().supportsBWC()) {
2206        return;
2207    }
2208    int src_w = crop.right - crop.left;
2209    int src_h = crop.bottom - crop.top;
2210    int dst_w = dst.right - dst.left;
2211    int dst_h = dst.bottom - dst.top;
2212    if(transform & HAL_TRANSFORM_ROT_90) {
2213        swap(src_w, src_h);
2214    }
2215    //src width > MAX mixer supported dim
2216    if(src_w > qdutils::MAX_DISPLAY_DIM) {
2217        return;
2218    }
2219    //Decimation necessary, cannot use BWC. H/W requirement.
2220    if(qdutils::MDPVersion::getInstance().supportsDecimation()) {
2221        uint8_t horzDeci = 0;
2222        uint8_t vertDeci = 0;
2223        ovutils::getDecimationFactor(src_w, src_h, dst_w, dst_h, horzDeci,
2224                vertDeci);
2225        if(horzDeci || vertDeci) return;
2226    }
2227    //Property
2228    char value[PROPERTY_VALUE_MAX];
2229    property_get("debug.disable.bwc", value, "0");
2230     if(atoi(value)) return;
2231
2232    ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDSS_MDP_BWC_EN);
2233}
2234
2235void LayerRotMap::add(hwc_layer_1_t* layer, Rotator *rot) {
2236    if(mCount >= MAX_SESS) return;
2237    mLayer[mCount] = layer;
2238    mRot[mCount] = rot;
2239    mCount++;
2240}
2241
2242void LayerRotMap::reset() {
2243    for (int i = 0; i < MAX_SESS; i++) {
2244        mLayer[i] = 0;
2245        mRot[i] = 0;
2246    }
2247    mCount = 0;
2248}
2249
2250void LayerRotMap::clear() {
2251    RotMgr::getInstance()->markUnusedTop(mCount);
2252    reset();
2253}
2254
2255void LayerRotMap::setReleaseFd(const int& fence) {
2256    for(uint32_t i = 0; i < mCount; i++) {
2257        mRot[i]->setReleaseFd(dup(fence));
2258    }
2259}
2260
2261void resetROI(hwc_context_t *ctx, const int dpy) {
2262    const int fbXRes = (int)ctx->dpyAttr[dpy].xres;
2263    const int fbYRes = (int)ctx->dpyAttr[dpy].yres;
2264    if(isDisplaySplit(ctx, dpy)) {
2265        const int lSplit = getLeftSplit(ctx, dpy);
2266        ctx->listStats[dpy].lRoi = (struct hwc_rect){0, 0, lSplit, fbYRes};
2267        ctx->listStats[dpy].rRoi = (struct hwc_rect){lSplit, 0, fbXRes, fbYRes};
2268    } else  {
2269        ctx->listStats[dpy].lRoi = (struct hwc_rect){0, 0,fbXRes, fbYRes};
2270        ctx->listStats[dpy].rRoi = (struct hwc_rect){0, 0, 0, 0};
2271    }
2272}
2273
2274hwc_rect_t getSanitizeROI(struct hwc_rect roi, hwc_rect boundary)
2275{
2276   if(!isValidRect(roi))
2277      return roi;
2278
2279   struct hwc_rect t_roi = roi;
2280
2281   const int LEFT_ALIGN = qdutils::MDPVersion::getInstance().getLeftAlign();
2282   const int WIDTH_ALIGN = qdutils::MDPVersion::getInstance().getWidthAlign();
2283   const int TOP_ALIGN = qdutils::MDPVersion::getInstance().getTopAlign();
2284   const int HEIGHT_ALIGN = qdutils::MDPVersion::getInstance().getHeightAlign();
2285   const int MIN_WIDTH = qdutils::MDPVersion::getInstance().getMinROIWidth();
2286   const int MIN_HEIGHT = qdutils::MDPVersion::getInstance().getMinROIHeight();
2287
2288   /* Align to minimum width recommended by the panel */
2289   if((t_roi.right - t_roi.left) < MIN_WIDTH) {
2290       if((t_roi.left + MIN_WIDTH) > boundary.right)
2291           t_roi.left = t_roi.right - MIN_WIDTH;
2292       else
2293           t_roi.right = t_roi.left + MIN_WIDTH;
2294   }
2295
2296  /* Align to minimum height recommended by the panel */
2297   if((t_roi.bottom - t_roi.top) < MIN_HEIGHT) {
2298       if((t_roi.top + MIN_HEIGHT) > boundary.bottom)
2299           t_roi.top = t_roi.bottom - MIN_HEIGHT;
2300       else
2301           t_roi.bottom = t_roi.top + MIN_HEIGHT;
2302   }
2303
2304   /* Align left and width to meet panel restrictions */
2305   if(LEFT_ALIGN)
2306       t_roi.left = t_roi.left - (t_roi.left % LEFT_ALIGN);
2307
2308   if(WIDTH_ALIGN) {
2309       int width = t_roi.right - t_roi.left;
2310       width = WIDTH_ALIGN * ((width + (WIDTH_ALIGN - 1)) / WIDTH_ALIGN);
2311       t_roi.right = t_roi.left + width;
2312
2313       if(t_roi.right > boundary.right) {
2314           t_roi.right = boundary.right;
2315           t_roi.left = t_roi.right - width;
2316
2317           if(LEFT_ALIGN)
2318               t_roi.left = t_roi.left - (t_roi.left % LEFT_ALIGN);
2319       }
2320   }
2321
2322
2323   /* Align top and height to meet panel restrictions */
2324   if(TOP_ALIGN)
2325       t_roi.top = t_roi.top - (t_roi.top % TOP_ALIGN);
2326
2327   if(HEIGHT_ALIGN) {
2328       int height = t_roi.bottom - t_roi.top;
2329       height = HEIGHT_ALIGN *  ((height + (HEIGHT_ALIGN - 1)) / HEIGHT_ALIGN);
2330       t_roi.bottom = t_roi.top  + height;
2331
2332       if(t_roi.bottom > boundary.bottom) {
2333           t_roi.bottom = boundary.bottom;
2334           t_roi.top = t_roi.bottom - height;
2335
2336           if(TOP_ALIGN)
2337               t_roi.top = t_roi.top - (t_roi.top % TOP_ALIGN);
2338       }
2339   }
2340
2341
2342   return t_roi;
2343}
2344
2345};//namespace qhwc
2346