hwc_utils.cpp revision cfb968873b9e94dca883aadabee42b01558faea9
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        } else {
1315            close(currLayer->acquireFenceFd);
1316            //For MDP to wait on.
1317            currLayer->acquireFenceFd =
1318                    dup(rotReleaseFd);
1319            //A buffer is free to be used by producer as soon as its copied to
1320            //rotator
1321            currLayer->releaseFenceFd =
1322                    rotReleaseFd;
1323        }
1324    }
1325
1326    //Accumulate acquireFenceFds for MDP Overlays
1327    if(list->outbufAcquireFenceFd >= 0) {
1328        //Writeback output buffer
1329        acquireFd[count++] = list->outbufAcquireFenceFd;
1330    }
1331
1332    for(uint32_t i = 0; i < list->numHwLayers; i++) {
1333        if(((isAbcInUse(ctx)== true ) ||
1334          (list->hwLayers[i].compositionType == HWC_OVERLAY)) &&
1335                        list->hwLayers[i].acquireFenceFd >= 0) {
1336            if(UNLIKELY(swapzero))
1337                acquireFd[count++] = -1;
1338            // if ABC is enabled for more than one layer.
1339            // renderBufIndexforABC will work as FB.Hence
1340            // set the acquireFD from fd - which is coming from copybit
1341            else if(fd >= 0 && (isAbcInUse(ctx) == true)) {
1342                if(ctx->listStats[dpy].renderBufIndexforABC ==(int32_t)i)
1343                   acquireFd[count++] = fd;
1344                else
1345                   continue;
1346            } else
1347                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
1348        }
1349        if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
1350            if(UNLIKELY(swapzero))
1351                acquireFd[count++] = -1;
1352            else if(fd >= 0) {
1353                //set the acquireFD from fd - which is coming from c2d
1354                acquireFd[count++] = fd;
1355                // Buffer sync IOCTL should be async when using c2d fence is
1356                // used
1357                data.flags &= ~MDP_BUF_SYNC_FLAG_WAIT;
1358            } else if(list->hwLayers[i].acquireFenceFd >= 0)
1359                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
1360        }
1361    }
1362
1363    if ((fd >= 0) && !dpy && ctx->mMDPComp[dpy]->isPTORActive()) {
1364        // Acquire c2d fence of Overlap render buffer
1365        acquireFd[count++] = fd;
1366    }
1367
1368    data.acq_fen_fd_cnt = count;
1369    fbFd = ctx->dpyAttr[dpy].fd;
1370
1371    //Waits for acquire fences, returns a release fence
1372    if(LIKELY(!swapzero)) {
1373        ret = ioctl(fbFd, MSMFB_BUFFER_SYNC, &data);
1374    }
1375
1376    if(ret < 0) {
1377        ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed, err=%s",
1378                  __FUNCTION__, strerror(errno));
1379        ALOGE("%s: acq_fen_fd_cnt=%d flags=%d fd=%d dpy=%d numHwLayers=%zu",
1380              __FUNCTION__, data.acq_fen_fd_cnt, data.flags, fbFd,
1381              dpy, list->numHwLayers);
1382    }
1383
1384    for(uint32_t i = 0; i < list->numHwLayers; i++) {
1385        if(list->hwLayers[i].compositionType == HWC_OVERLAY ||
1386#ifdef QCOM_BSP
1387           list->hwLayers[i].compositionType == HWC_BLIT ||
1388#endif
1389           list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
1390            //Populate releaseFenceFds.
1391            if(UNLIKELY(swapzero)) {
1392                list->hwLayers[i].releaseFenceFd = -1;
1393            } else if(isExtAnimating) {
1394                // Release all the app layer fds immediately,
1395                // if animation is in progress.
1396                list->hwLayers[i].releaseFenceFd = -1;
1397            } else if(list->hwLayers[i].releaseFenceFd < 0 ) {
1398#ifdef QCOM_BSP
1399                //If rotator has not already populated this field
1400                // & if it's a not VPU layer
1401
1402                // if ABC is enabled for more than one layer
1403                if(fd >= 0 && (isAbcInUse(ctx) == true) &&
1404                  ctx->listStats[dpy].renderBufIndexforABC !=(int32_t)i){
1405                    list->hwLayers[i].releaseFenceFd = dup(fd);
1406                } else if((list->hwLayers[i].compositionType == HWC_BLIT)&&
1407                                               (isAbcInUse(ctx) == false)){
1408                    //For Blit, the app layers should be released when the Blit
1409                    //is complete. This fd was passed from copybit->draw
1410                    list->hwLayers[i].releaseFenceFd = dup(fd);
1411                } else
1412#endif
1413                {
1414                    list->hwLayers[i].releaseFenceFd = dup(releaseFd);
1415                }
1416            }
1417        }
1418    }
1419
1420    if(fd >= 0) {
1421        close(fd);
1422        fd = -1;
1423    }
1424
1425    if (!dpy && ctx->mCopyBit[dpy]) {
1426        if (ctx->mMDPComp[dpy]->isPTORActive())
1427            ctx->mCopyBit[dpy]->setReleaseFdSync(releaseFd);
1428        else
1429            ctx->mCopyBit[dpy]->setReleaseFd(releaseFd);
1430    }
1431
1432    //Signals when MDP finishes reading rotator buffers.
1433    ctx->mLayerRotMap[dpy]->setReleaseFd(releaseFd);
1434    close(releaseFd);
1435    releaseFd = -1;
1436
1437    if(UNLIKELY(swapzero)) {
1438        list->retireFenceFd = -1;
1439    } else {
1440        list->retireFenceFd = retireFd;
1441    }
1442    return ret;
1443}
1444
1445void setMdpFlags(hwc_context_t *ctx, hwc_layer_1_t *layer,
1446        ovutils::eMdpFlags &mdpFlags,
1447        int rotDownscale, int transform) {
1448    private_handle_t *hnd = (private_handle_t *)layer->handle;
1449    MetaData_t *metadata = hnd ? (MetaData_t *)hnd->base_metadata : NULL;
1450
1451    if(layer->blending == HWC_BLENDING_PREMULT) {
1452        ovutils::setMdpFlags(mdpFlags,
1453                ovutils::OV_MDP_BLEND_FG_PREMULT);
1454    }
1455
1456    if(isYuvBuffer(hnd)) {
1457        if(isSecureBuffer(hnd)) {
1458            ovutils::setMdpFlags(mdpFlags,
1459                    ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
1460        }
1461        if(metadata && (metadata->operation & PP_PARAM_INTERLACED) &&
1462                metadata->interlaced) {
1463            ovutils::setMdpFlags(mdpFlags,
1464                    ovutils::OV_MDP_DEINTERLACE);
1465        }
1466    }
1467
1468    if(isSecureDisplayBuffer(hnd)) {
1469        // Secure display needs both SECURE_OVERLAY and SECURE_DISPLAY_OV
1470        ovutils::setMdpFlags(mdpFlags,
1471                             ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
1472        ovutils::setMdpFlags(mdpFlags,
1473                             ovutils::OV_MDP_SECURE_DISPLAY_OVERLAY_SESSION);
1474    }
1475
1476    //Pre-rotation will be used using rotator.
1477    if(has90Transform(layer) && isRotationDoable(ctx, hnd)) {
1478        ovutils::setMdpFlags(mdpFlags,
1479                ovutils::OV_MDP_SOURCE_ROTATED_90);
1480    }
1481    //No 90 component and no rot-downscale then flips done by MDP
1482    //If we use rot then it might as well do flips
1483    if(!(transform & HWC_TRANSFORM_ROT_90) && !rotDownscale) {
1484        if(transform & HWC_TRANSFORM_FLIP_H) {
1485            ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_FLIP_H);
1486        }
1487
1488        if(transform & HWC_TRANSFORM_FLIP_V) {
1489            ovutils::setMdpFlags(mdpFlags,  ovutils::OV_MDP_FLIP_V);
1490        }
1491    }
1492
1493    if(metadata &&
1494        ((metadata->operation & PP_PARAM_HSIC)
1495        || (metadata->operation & PP_PARAM_IGC)
1496        || (metadata->operation & PP_PARAM_SHARP2))) {
1497        ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_PP_EN);
1498    }
1499}
1500
1501int configRotator(Rotator *rot, Whf& whf,
1502        hwc_rect_t& crop, const eMdpFlags& mdpFlags,
1503        const eTransform& orient, const int& downscale) {
1504
1505    // Fix alignments for TILED format
1506    if(whf.format == MDP_Y_CRCB_H2V2_TILE ||
1507                            whf.format == MDP_Y_CBCR_H2V2_TILE) {
1508        whf.w =  utils::alignup(whf.w, 64);
1509        whf.h = utils::alignup(whf.h, 32);
1510    }
1511    rot->setSource(whf);
1512
1513    if (qdutils::MDPVersion::getInstance().getMDPVersion() >=
1514        qdutils::MDSS_V5) {
1515        uint32_t crop_w = (crop.right - crop.left);
1516        uint32_t crop_h = (crop.bottom - crop.top);
1517        if (ovutils::isYuv(whf.format)) {
1518            ovutils::normalizeCrop((uint32_t&)crop.left, crop_w);
1519            ovutils::normalizeCrop((uint32_t&)crop.top, crop_h);
1520            // For interlaced, crop.h should be 4-aligned
1521            if ((mdpFlags & ovutils::OV_MDP_DEINTERLACE) && (crop_h % 4))
1522                crop_h = ovutils::aligndown(crop_h, 4);
1523            crop.right = crop.left + crop_w;
1524            crop.bottom = crop.top + crop_h;
1525        }
1526        Dim rotCrop(crop.left, crop.top, crop_w, crop_h);
1527        rot->setCrop(rotCrop);
1528    }
1529
1530    rot->setFlags(mdpFlags);
1531    rot->setTransform(orient);
1532    rot->setDownscale(downscale);
1533    if(!rot->commit()) return -1;
1534    return 0;
1535}
1536
1537int configMdp(Overlay *ov, const PipeArgs& parg,
1538        const eTransform& orient, const hwc_rect_t& crop,
1539        const hwc_rect_t& pos, const MetaData_t *metadata,
1540        const eDest& dest) {
1541    ov->setSource(parg, dest);
1542    ov->setTransform(orient, dest);
1543
1544    int crop_w = crop.right - crop.left;
1545    int crop_h = crop.bottom - crop.top;
1546    Dim dcrop(crop.left, crop.top, crop_w, crop_h);
1547    ov->setCrop(dcrop, dest);
1548
1549    int posW = pos.right - pos.left;
1550    int posH = pos.bottom - pos.top;
1551    Dim position(pos.left, pos.top, posW, posH);
1552    ov->setPosition(position, dest);
1553
1554    if (metadata)
1555        ov->setVisualParams(*metadata, dest);
1556
1557    if (!ov->commit(dest)) {
1558        return -1;
1559    }
1560    return 0;
1561}
1562
1563int configColorLayer(hwc_context_t *ctx, hwc_layer_1_t *layer,
1564        const int& dpy, eMdpFlags& mdpFlags, eZorder& z,
1565        eIsFg& isFg, const eDest& dest) {
1566
1567    hwc_rect_t dst = layer->displayFrame;
1568    trimLayer(ctx, dpy, 0, dst, dst);
1569
1570    int w = ctx->dpyAttr[dpy].xres;
1571    int h = ctx->dpyAttr[dpy].yres;
1572    int dst_w = dst.right - dst.left;
1573    int dst_h = dst.bottom - dst.top;
1574    uint32_t color = layer->transform;
1575    Whf whf(w, h, getMdpFormat(HAL_PIXEL_FORMAT_RGBA_8888), 0);
1576
1577    ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_SOLID_FILL);
1578    if (layer->blending == HWC_BLENDING_PREMULT)
1579        ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_BLEND_FG_PREMULT);
1580
1581    PipeArgs parg(mdpFlags, whf, z, isFg, static_cast<eRotFlags>(0),
1582                  layer->planeAlpha,
1583                  (ovutils::eBlending) getBlending(layer->blending));
1584
1585    // Configure MDP pipe for Color layer
1586    Dim pos(dst.left, dst.top, dst_w, dst_h);
1587    ctx->mOverlay->setSource(parg, dest);
1588    ctx->mOverlay->setColor(color, dest);
1589    ctx->mOverlay->setTransform(0, dest);
1590    ctx->mOverlay->setCrop(pos, dest);
1591    ctx->mOverlay->setPosition(pos, dest);
1592
1593    if (!ctx->mOverlay->commit(dest)) {
1594        ALOGE("%s: Configure color layer failed!", __FUNCTION__);
1595        return -1;
1596    }
1597    return 0;
1598}
1599
1600void updateSource(eTransform& orient, Whf& whf,
1601        hwc_rect_t& crop) {
1602    Dim srcCrop(crop.left, crop.top,
1603            crop.right - crop.left,
1604            crop.bottom - crop.top);
1605    orient = static_cast<eTransform>(ovutils::getMdpOrient(orient));
1606    preRotateSource(orient, whf, srcCrop);
1607    if (qdutils::MDPVersion::getInstance().getMDPVersion() >=
1608        qdutils::MDSS_V5) {
1609        // Source for overlay will be the cropped (and rotated)
1610        crop.left = 0;
1611        crop.top = 0;
1612        crop.right = srcCrop.w;
1613        crop.bottom = srcCrop.h;
1614        // Set width & height equal to sourceCrop w & h
1615        whf.w = srcCrop.w;
1616        whf.h = srcCrop.h;
1617    } else {
1618        crop.left = srcCrop.x;
1619        crop.top = srcCrop.y;
1620        crop.right = srcCrop.x + srcCrop.w;
1621        crop.bottom = srcCrop.y + srcCrop.h;
1622    }
1623}
1624
1625int configureNonSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
1626        const int& dpy, eMdpFlags& mdpFlags, eZorder& z,
1627        eIsFg& isFg, const eDest& dest, Rotator **rot) {
1628
1629    private_handle_t *hnd = (private_handle_t *)layer->handle;
1630
1631    if(!hnd) {
1632        if (layer->flags & HWC_COLOR_FILL) {
1633            // Configure Color layer
1634            return configColorLayer(ctx, layer, dpy, mdpFlags, z, isFg, dest);
1635        }
1636        ALOGE("%s: layer handle is NULL", __FUNCTION__);
1637        return -1;
1638    }
1639
1640    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
1641
1642    hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
1643    hwc_rect_t dst = layer->displayFrame;
1644    int transform = layer->transform;
1645    eTransform orient = static_cast<eTransform>(transform);
1646    int downscale = 0;
1647    int rotFlags = ovutils::ROT_FLAGS_NONE;
1648    uint32_t format = ovutils::getMdpFormat(hnd->format, isTileRendered(hnd));
1649    Whf whf(getWidth(hnd), getHeight(hnd), format, (uint32_t)hnd->size);
1650
1651    // Handle R/B swap
1652    if (layer->flags & HWC_FORMAT_RB_SWAP) {
1653        if (hnd->format == HAL_PIXEL_FORMAT_RGBA_8888)
1654            whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRA_8888);
1655        else if (hnd->format == HAL_PIXEL_FORMAT_RGBX_8888)
1656            whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRX_8888);
1657    }
1658
1659    calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient);
1660
1661    if(isYuvBuffer(hnd) && ctx->mMDP.version >= qdutils::MDP_V4_2 &&
1662       ctx->mMDP.version < qdutils::MDSS_V5) {
1663        downscale =  getDownscaleFactor(
1664            crop.right - crop.left,
1665            crop.bottom - crop.top,
1666            dst.right - dst.left,
1667            dst.bottom - dst.top);
1668        if(downscale) {
1669            rotFlags = ROT_DOWNSCALE_ENABLED;
1670        }
1671    }
1672
1673    setMdpFlags(ctx, layer, mdpFlags, downscale, transform);
1674
1675    //if 90 component or downscale, use rot
1676    if((has90Transform(layer) && isRotationDoable(ctx, hnd)) || downscale) {
1677        *rot = ctx->mRotMgr->getNext();
1678        if(*rot == NULL) return -1;
1679        ctx->mLayerRotMap[dpy]->add(layer, *rot);
1680        // BWC is not tested for other formats So enable it only for YUV format
1681        if(!dpy && isYuvBuffer(hnd))
1682            BwcPM::setBwc(crop, dst, transform, mdpFlags);
1683        //Configure rotator for pre-rotation
1684        if(configRotator(*rot, whf, crop, mdpFlags, orient, downscale) < 0) {
1685            ALOGE("%s: configRotator failed!", __FUNCTION__);
1686            return -1;
1687        }
1688        whf.format = (*rot)->getDstFormat();
1689        updateSource(orient, whf, crop);
1690        rotFlags |= ovutils::ROT_PREROTATED;
1691    }
1692
1693    //For the mdp, since either we are pre-rotating or MDP does flips
1694    orient = OVERLAY_TRANSFORM_0;
1695    transform = 0;
1696    PipeArgs parg(mdpFlags, whf, z, isFg,
1697                  static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
1698                  (ovutils::eBlending) getBlending(layer->blending));
1699
1700    if(configMdp(ctx->mOverlay, parg, orient, crop, dst, metadata, dest) < 0) {
1701        ALOGE("%s: commit failed for low res panel", __FUNCTION__);
1702        return -1;
1703    }
1704    return 0;
1705}
1706
1707//Helper to 1) Ensure crops dont have gaps 2) Ensure L and W are even
1708void sanitizeSourceCrop(hwc_rect_t& cropL, hwc_rect_t& cropR,
1709        private_handle_t *hnd) {
1710    if(cropL.right - cropL.left) {
1711        if(isYuvBuffer(hnd)) {
1712            //Always safe to even down left
1713            ovutils::even_floor(cropL.left);
1714            //If right is even, automatically width is even, since left is
1715            //already even
1716            ovutils::even_floor(cropL.right);
1717        }
1718        //Make sure there are no gaps between left and right splits if the layer
1719        //is spread across BOTH halves
1720        if(cropR.right - cropR.left) {
1721            cropR.left = cropL.right;
1722        }
1723    }
1724
1725    if(cropR.right - cropR.left) {
1726        if(isYuvBuffer(hnd)) {
1727            //Always safe to even down left
1728            ovutils::even_floor(cropR.left);
1729            //If right is even, automatically width is even, since left is
1730            //already even
1731            ovutils::even_floor(cropR.right);
1732        }
1733    }
1734}
1735
1736int configureSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
1737        const int& dpy, eMdpFlags& mdpFlagsL, eZorder& z,
1738        eIsFg& isFg, const eDest& lDest, const eDest& rDest,
1739        Rotator **rot) {
1740    private_handle_t *hnd = (private_handle_t *)layer->handle;
1741    if(!hnd) {
1742        ALOGE("%s: layer handle is NULL", __FUNCTION__);
1743        return -1;
1744    }
1745
1746    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
1747
1748    int hw_w = ctx->dpyAttr[dpy].xres;
1749    int hw_h = ctx->dpyAttr[dpy].yres;
1750    hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
1751    hwc_rect_t dst = layer->displayFrame;
1752    int transform = layer->transform;
1753    eTransform orient = static_cast<eTransform>(transform);
1754    const int downscale = 0;
1755    int rotFlags = ROT_FLAGS_NONE;
1756    uint32_t format = ovutils::getMdpFormat(hnd->format, isTileRendered(hnd));
1757    Whf whf(getWidth(hnd), getHeight(hnd), format, (uint32_t)hnd->size);
1758
1759    // Handle R/B swap
1760    if (layer->flags & HWC_FORMAT_RB_SWAP) {
1761        if (hnd->format == HAL_PIXEL_FORMAT_RGBA_8888)
1762            whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRA_8888);
1763        else if (hnd->format == HAL_PIXEL_FORMAT_RGBX_8888)
1764            whf.format = getMdpFormat(HAL_PIXEL_FORMAT_BGRX_8888);
1765    }
1766
1767    /* Calculate the external display position based on MDP downscale,
1768       ActionSafe, and extorientation features. */
1769    calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient);
1770
1771    setMdpFlags(ctx, layer, mdpFlagsL, 0, transform);
1772
1773    if(lDest != OV_INVALID && rDest != OV_INVALID) {
1774        //Enable overfetch
1775        setMdpFlags(mdpFlagsL, OV_MDSS_MDP_DUAL_PIPE);
1776    }
1777
1778    //Will do something only if feature enabled and conditions suitable
1779    //hollow call otherwise
1780    if(ctx->mAD->prepare(ctx, crop, whf, hnd)) {
1781        overlay::Writeback *wb = overlay::Writeback::getInstance();
1782        whf.format = wb->getOutputFormat();
1783    }
1784
1785    if(has90Transform(layer) && isRotationDoable(ctx, hnd)) {
1786        (*rot) = ctx->mRotMgr->getNext();
1787        if((*rot) == NULL) return -1;
1788        ctx->mLayerRotMap[dpy]->add(layer, *rot);
1789        //Configure rotator for pre-rotation
1790        if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale) < 0) {
1791            ALOGE("%s: configRotator failed!", __FUNCTION__);
1792            return -1;
1793        }
1794        whf.format = (*rot)->getDstFormat();
1795        updateSource(orient, whf, crop);
1796        rotFlags |= ROT_PREROTATED;
1797    }
1798
1799    eMdpFlags mdpFlagsR = mdpFlagsL;
1800    setMdpFlags(mdpFlagsR, OV_MDSS_MDP_RIGHT_MIXER);
1801
1802    hwc_rect_t tmp_cropL = {0}, tmp_dstL = {0};
1803    hwc_rect_t tmp_cropR = {0}, tmp_dstR = {0};
1804
1805    const int lSplit = getLeftSplit(ctx, dpy);
1806
1807    // Calculate Left rects
1808    if(dst.left < lSplit) {
1809        tmp_cropL = crop;
1810        tmp_dstL = dst;
1811        hwc_rect_t scissor = {0, 0, lSplit, hw_h };
1812        scissor = getIntersection(ctx->mViewFrame[dpy], scissor);
1813        qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
1814    }
1815
1816    // Calculate Right rects
1817    if(dst.right > lSplit) {
1818        tmp_cropR = crop;
1819        tmp_dstR = dst;
1820        hwc_rect_t scissor = {lSplit, 0, hw_w, hw_h };
1821        scissor = getIntersection(ctx->mViewFrame[dpy], scissor);
1822        qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
1823    }
1824
1825    sanitizeSourceCrop(tmp_cropL, tmp_cropR, hnd);
1826
1827    //When buffer is H-flipped, contents of mixer config also needs to swapped
1828    //Not needed if the layer is confined to one half of the screen.
1829    //If rotator has been used then it has also done the flips, so ignore them.
1830    if((orient & OVERLAY_TRANSFORM_FLIP_H) && (dst.left < lSplit) &&
1831            (dst.right > lSplit) && (*rot) == NULL) {
1832        hwc_rect_t new_cropR;
1833        new_cropR.left = tmp_cropL.left;
1834        new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
1835
1836        hwc_rect_t new_cropL;
1837        new_cropL.left  = new_cropR.right;
1838        new_cropL.right = tmp_cropR.right;
1839
1840        tmp_cropL.left =  new_cropL.left;
1841        tmp_cropL.right =  new_cropL.right;
1842
1843        tmp_cropR.left = new_cropR.left;
1844        tmp_cropR.right =  new_cropR.right;
1845
1846    }
1847
1848    //For the mdp, since either we are pre-rotating or MDP does flips
1849    orient = OVERLAY_TRANSFORM_0;
1850    transform = 0;
1851
1852    //configure left mixer
1853    if(lDest != OV_INVALID) {
1854        PipeArgs pargL(mdpFlagsL, whf, z, isFg,
1855                       static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
1856                       (ovutils::eBlending) getBlending(layer->blending));
1857
1858        if(configMdp(ctx->mOverlay, pargL, orient,
1859                tmp_cropL, tmp_dstL, metadata, lDest) < 0) {
1860            ALOGE("%s: commit failed for left mixer config", __FUNCTION__);
1861            return -1;
1862        }
1863    }
1864
1865    //configure right mixer
1866    if(rDest != OV_INVALID) {
1867        PipeArgs pargR(mdpFlagsR, whf, z, isFg,
1868                       static_cast<eRotFlags>(rotFlags),
1869                       layer->planeAlpha,
1870                       (ovutils::eBlending) getBlending(layer->blending));
1871        tmp_dstR.right = tmp_dstR.right - lSplit;
1872        tmp_dstR.left = tmp_dstR.left - lSplit;
1873        if(configMdp(ctx->mOverlay, pargR, orient,
1874                tmp_cropR, tmp_dstR, metadata, rDest) < 0) {
1875            ALOGE("%s: commit failed for right mixer config", __FUNCTION__);
1876            return -1;
1877        }
1878    }
1879
1880    return 0;
1881}
1882
1883int configureSourceSplit(hwc_context_t *ctx, hwc_layer_1_t *layer,
1884        const int& dpy, eMdpFlags& mdpFlagsL, eZorder& z,
1885        eIsFg& isFg, const eDest& lDest, const eDest& rDest,
1886        Rotator **rot) {
1887    private_handle_t *hnd = (private_handle_t *)layer->handle;
1888    if(!hnd) {
1889        ALOGE("%s: layer handle is NULL", __FUNCTION__);
1890        return -1;
1891    }
1892
1893    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
1894
1895    hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);;
1896    hwc_rect_t dst = layer->displayFrame;
1897    int transform = layer->transform;
1898    eTransform orient = static_cast<eTransform>(transform);
1899    const int downscale = 0;
1900    int rotFlags = ROT_FLAGS_NONE;
1901    //Splitting only YUV layer on primary panel needs different zorders
1902    //for both layers as both the layers are configured to single mixer
1903    eZorder lz = z;
1904    eZorder rz = (eZorder)(z + 1);
1905
1906    Whf whf(getWidth(hnd), getHeight(hnd),
1907            getMdpFormat(hnd->format), (uint32_t)hnd->size);
1908
1909    /* Calculate the external display position based on MDP downscale,
1910       ActionSafe, and extorientation features. */
1911    calcExtDisplayPosition(ctx, hnd, dpy, crop, dst, transform, orient);
1912
1913    setMdpFlags(ctx, layer, mdpFlagsL, 0, transform);
1914    trimLayer(ctx, dpy, transform, crop, dst);
1915
1916    if(has90Transform(layer) && isRotationDoable(ctx, hnd)) {
1917        (*rot) = ctx->mRotMgr->getNext();
1918        if((*rot) == NULL) return -1;
1919        ctx->mLayerRotMap[dpy]->add(layer, *rot);
1920        // BWC is not tested for other formats So enable it only for YUV format
1921        if(!dpy && isYuvBuffer(hnd))
1922            BwcPM::setBwc(crop, dst, transform, mdpFlagsL);
1923        //Configure rotator for pre-rotation
1924        if(configRotator(*rot, whf, crop, mdpFlagsL, orient, downscale) < 0) {
1925            ALOGE("%s: configRotator failed!", __FUNCTION__);
1926            return -1;
1927        }
1928        whf.format = (*rot)->getDstFormat();
1929        updateSource(orient, whf, crop);
1930        rotFlags |= ROT_PREROTATED;
1931    }
1932
1933    eMdpFlags mdpFlagsR = mdpFlagsL;
1934    int lSplit = dst.left + (dst.right - dst.left)/2;
1935
1936    hwc_rect_t tmp_cropL = {0}, tmp_dstL = {0};
1937    hwc_rect_t tmp_cropR = {0}, tmp_dstR = {0};
1938
1939    if(lDest != OV_INVALID) {
1940        tmp_cropL = crop;
1941        tmp_dstL = dst;
1942        hwc_rect_t scissor = {dst.left, dst.top, lSplit, dst.bottom };
1943        qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
1944    }
1945    if(rDest != OV_INVALID) {
1946        tmp_cropR = crop;
1947        tmp_dstR = dst;
1948        hwc_rect_t scissor = {lSplit, dst.top, dst.right, dst.bottom };
1949        qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
1950    }
1951
1952    sanitizeSourceCrop(tmp_cropL, tmp_cropR, hnd);
1953
1954    //When buffer is H-flipped, contents of mixer config also needs to swapped
1955    //Not needed if the layer is confined to one half of the screen.
1956    //If rotator has been used then it has also done the flips, so ignore them.
1957    if((orient & OVERLAY_TRANSFORM_FLIP_H) && lDest != OV_INVALID
1958            && rDest != OV_INVALID && (*rot) == NULL) {
1959        hwc_rect_t new_cropR;
1960        new_cropR.left = tmp_cropL.left;
1961        new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
1962
1963        hwc_rect_t new_cropL;
1964        new_cropL.left  = new_cropR.right;
1965        new_cropL.right = tmp_cropR.right;
1966
1967        tmp_cropL.left =  new_cropL.left;
1968        tmp_cropL.right =  new_cropL.right;
1969
1970        tmp_cropR.left = new_cropR.left;
1971        tmp_cropR.right =  new_cropR.right;
1972
1973    }
1974
1975    //For the mdp, since either we are pre-rotating or MDP does flips
1976    orient = OVERLAY_TRANSFORM_0;
1977    transform = 0;
1978
1979    //configure left half
1980    if(lDest != OV_INVALID) {
1981        PipeArgs pargL(mdpFlagsL, whf, lz, isFg,
1982                static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
1983                (ovutils::eBlending) getBlending(layer->blending));
1984
1985        if(configMdp(ctx->mOverlay, pargL, orient,
1986                    tmp_cropL, tmp_dstL, metadata, lDest) < 0) {
1987            ALOGE("%s: commit failed for left half config", __FUNCTION__);
1988            return -1;
1989        }
1990    }
1991
1992    //configure right half
1993    if(rDest != OV_INVALID) {
1994        PipeArgs pargR(mdpFlagsR, whf, rz, isFg,
1995                static_cast<eRotFlags>(rotFlags),
1996                layer->planeAlpha,
1997                (ovutils::eBlending) getBlending(layer->blending));
1998        if(configMdp(ctx->mOverlay, pargR, orient,
1999                    tmp_cropR, tmp_dstR, metadata, rDest) < 0) {
2000            ALOGE("%s: commit failed for right half config", __FUNCTION__);
2001            return -1;
2002        }
2003    }
2004
2005    return 0;
2006}
2007
2008bool canUseRotator(hwc_context_t *ctx, int dpy) {
2009    if(ctx->mOverlay->isDMAMultiplexingSupported() &&
2010            isSecondaryConnected(ctx) &&
2011            !ctx->dpyAttr[HWC_DISPLAY_VIRTUAL].isPause) {
2012        /* mdss driver on certain targets support multiplexing of DMA pipe
2013         * in LINE and BLOCK modes for writeback panels.
2014         */
2015        if(dpy == HWC_DISPLAY_PRIMARY)
2016            return false;
2017    }
2018    if(ctx->mMDP.version == qdutils::MDP_V3_0_4)
2019        return false;
2020    return true;
2021}
2022
2023int getLeftSplit(hwc_context_t *ctx, const int& dpy) {
2024    //Default even split for all displays with high res
2025    int lSplit = ctx->dpyAttr[dpy].xres / 2;
2026    if(dpy == HWC_DISPLAY_PRIMARY &&
2027            qdutils::MDPVersion::getInstance().getLeftSplit()) {
2028        //Override if split published by driver for primary
2029        lSplit = qdutils::MDPVersion::getInstance().getLeftSplit();
2030    }
2031    return lSplit;
2032}
2033
2034bool isDisplaySplit(hwc_context_t* ctx, int dpy) {
2035    if(ctx->dpyAttr[dpy].xres > qdutils::MAX_DISPLAY_DIM) {
2036        return true;
2037    }
2038    //For testing we could split primary via device tree values
2039    if(dpy == HWC_DISPLAY_PRIMARY &&
2040        qdutils::MDPVersion::getInstance().getRightSplit()) {
2041        return true;
2042    }
2043    return false;
2044}
2045
2046//clear prev layer prop flags and realloc for current frame
2047void reset_layer_prop(hwc_context_t* ctx, int dpy, int numAppLayers) {
2048    if(ctx->layerProp[dpy]) {
2049       delete[] ctx->layerProp[dpy];
2050       ctx->layerProp[dpy] = NULL;
2051    }
2052    ctx->layerProp[dpy] = new LayerProp[numAppLayers];
2053}
2054
2055bool isAbcInUse(hwc_context_t *ctx){
2056  return (ctx->enableABC && ctx->listStats[0].renderBufIndexforABC == 0);
2057}
2058
2059/* Since we fake non-Hybrid WFD solution as external display, this
2060 * function helps us in determining the priority between external
2061 * (hdmi/non-Hybrid WFD display) and virtual display devices(SSD/
2062 * screenrecord). This can be removed once wfd-client migrates to
2063 * using virtual-display api's.
2064 */
2065bool canUseMDPforVirtualDisplay(hwc_context_t* ctx,
2066                                const hwc_display_contents_1_t *list) {
2067
2068    /* We rely on the fact that for pure virtual display solution
2069     * list->outbuf will be a non-NULL handle.
2070     *
2071     * If there are three active displays (which means there is one
2072     * primary, one external and one virtual active display)
2073     * we give mdss/mdp hw resources(pipes,smp,etc) for external
2074     * display(hdmi/non-Hybrid WFD display) rather than for virtual
2075     * display(SSD/screenrecord)
2076     */
2077
2078    if(list->outbuf and (ctx->numActiveDisplays == HWC_NUM_DISPLAY_TYPES)) {
2079        return false;
2080    }
2081
2082    return true;
2083}
2084
2085void dumpBuffer(private_handle_t *ohnd, char *bufferName) {
2086    if (ohnd != NULL && ohnd->base) {
2087        char dumpFilename[PATH_MAX];
2088        bool bResult = false;
2089        snprintf(dumpFilename, sizeof(dumpFilename), "/data/%s.%s.%dx%d.raw",
2090            bufferName,
2091            overlay::utils::getFormatString(utils::getMdpFormat(ohnd->format)),
2092            getWidth(ohnd), getHeight(ohnd));
2093        FILE* fp = fopen(dumpFilename, "w+");
2094        if (NULL != fp) {
2095            bResult = (bool) fwrite((void*)ohnd->base, ohnd->size, 1, fp);
2096            fclose(fp);
2097        }
2098        ALOGD("Buffer[%s] Dump to %s: %s",
2099        bufferName, dumpFilename, bResult ? "Success" : "Fail");
2100    }
2101}
2102
2103bool isGLESComp(hwc_context_t *ctx,
2104                     hwc_display_contents_1_t* list) {
2105    int numAppLayers = ctx->listStats[HWC_DISPLAY_PRIMARY].numAppLayers;
2106    for(int index = 0; index < numAppLayers; index++) {
2107        hwc_layer_1_t* layer = &(list->hwLayers[index]);
2108        if(layer->compositionType == HWC_FRAMEBUFFER)
2109            return true;
2110    }
2111    return false;
2112}
2113
2114void setGPUHint(hwc_context_t* ctx, hwc_display_contents_1_t* list) {
2115    struct gpu_hint_info *gpuHint = &ctx->mGPUHintInfo;
2116    if(!gpuHint->mGpuPerfModeEnable || !ctx || !list)
2117        return;
2118
2119#ifdef QCOM_BSP
2120    /* Set the GPU hint flag to high for MIXED/GPU composition only for
2121       first frame after MDP -> GPU/MIXED mode transition. Set the GPU
2122       hint to default if the previous composition is GPU or current GPU
2123       composition is due to idle fallback */
2124    if(!gpuHint->mEGLDisplay || !gpuHint->mEGLContext) {
2125        gpuHint->mEGLDisplay = eglGetCurrentDisplay();
2126        if(!gpuHint->mEGLDisplay) {
2127            ALOGW("%s Warning: EGL current display is NULL", __FUNCTION__);
2128            return;
2129        }
2130        gpuHint->mEGLContext = eglGetCurrentContext();
2131        if(!gpuHint->mEGLContext) {
2132            ALOGW("%s Warning: EGL current context is NULL", __FUNCTION__);
2133            return;
2134        }
2135    }
2136    if(isGLESComp(ctx, list)) {
2137        if(gpuHint->mCompositionState != COMPOSITION_STATE_GPU
2138            && !MDPComp::isIdleFallback()) {
2139            EGLint attr_list[] = {EGL_GPU_HINT_1,
2140                                  EGL_GPU_LEVEL_3,
2141                                  EGL_NONE };
2142            if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_3) &&
2143                !eglGpuPerfHintQCOM(gpuHint->mEGLDisplay,
2144                                    gpuHint->mEGLContext, attr_list)) {
2145                ALOGW("eglGpuPerfHintQCOM failed for Built in display");
2146            } else {
2147                gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_3;
2148                gpuHint->mCompositionState = COMPOSITION_STATE_GPU;
2149            }
2150        } else {
2151            EGLint attr_list[] = {EGL_GPU_HINT_1,
2152                                  EGL_GPU_LEVEL_0,
2153                                  EGL_NONE };
2154            if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_0) &&
2155                !eglGpuPerfHintQCOM(gpuHint->mEGLDisplay,
2156                                    gpuHint->mEGLContext, attr_list)) {
2157                ALOGW("eglGpuPerfHintQCOM failed for Built in display");
2158            } else {
2159                gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_0;
2160            }
2161            if(MDPComp::isIdleFallback()) {
2162                gpuHint->mCompositionState = COMPOSITION_STATE_IDLE_FALLBACK;
2163            }
2164        }
2165    } else {
2166        /* set the GPU hint flag to default for MDP composition */
2167        EGLint attr_list[] = {EGL_GPU_HINT_1,
2168                              EGL_GPU_LEVEL_0,
2169                              EGL_NONE };
2170        if((gpuHint->mCurrGPUPerfMode != EGL_GPU_LEVEL_0) &&
2171                !eglGpuPerfHintQCOM(gpuHint->mEGLDisplay,
2172                                    gpuHint->mEGLContext, attr_list)) {
2173            ALOGW("eglGpuPerfHintQCOM failed for Built in display");
2174        } else {
2175            gpuHint->mCurrGPUPerfMode = EGL_GPU_LEVEL_0;
2176        }
2177        gpuHint->mCompositionState = COMPOSITION_STATE_MDP;
2178    }
2179#endif
2180}
2181
2182bool isPeripheral(const hwc_rect_t& rect1, const hwc_rect_t& rect2) {
2183    // To be peripheral, 3 boundaries should match.
2184    uint8_t eqBounds = 0;
2185    if (rect1.left == rect2.left)
2186        eqBounds++;
2187    if (rect1.top == rect2.top)
2188        eqBounds++;
2189    if (rect1.right == rect2.right)
2190        eqBounds++;
2191    if (rect1.bottom == rect2.bottom)
2192        eqBounds++;
2193    return (eqBounds == 3);
2194}
2195
2196void BwcPM::setBwc(const hwc_rect_t& crop,
2197            const hwc_rect_t& dst, const int& transform,
2198            ovutils::eMdpFlags& mdpFlags) {
2199    //Target doesnt support Bwc
2200    if(!qdutils::MDPVersion::getInstance().supportsBWC()) {
2201        return;
2202    }
2203    int src_w = crop.right - crop.left;
2204    int src_h = crop.bottom - crop.top;
2205    int dst_w = dst.right - dst.left;
2206    int dst_h = dst.bottom - dst.top;
2207    if(transform & HAL_TRANSFORM_ROT_90) {
2208        swap(src_w, src_h);
2209    }
2210    //src width > MAX mixer supported dim
2211    if(src_w > qdutils::MAX_DISPLAY_DIM) {
2212        return;
2213    }
2214    //Decimation necessary, cannot use BWC. H/W requirement.
2215    if(qdutils::MDPVersion::getInstance().supportsDecimation()) {
2216        uint8_t horzDeci = 0;
2217        uint8_t vertDeci = 0;
2218        ovutils::getDecimationFactor(src_w, src_h, dst_w, dst_h, horzDeci,
2219                vertDeci);
2220        if(horzDeci || vertDeci) return;
2221    }
2222    //Property
2223    char value[PROPERTY_VALUE_MAX];
2224    property_get("debug.disable.bwc", value, "0");
2225     if(atoi(value)) return;
2226
2227    ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDSS_MDP_BWC_EN);
2228}
2229
2230void LayerRotMap::add(hwc_layer_1_t* layer, Rotator *rot) {
2231    if(mCount >= MAX_SESS) return;
2232    mLayer[mCount] = layer;
2233    mRot[mCount] = rot;
2234    mCount++;
2235}
2236
2237void LayerRotMap::reset() {
2238    for (int i = 0; i < MAX_SESS; i++) {
2239        mLayer[i] = 0;
2240        mRot[i] = 0;
2241    }
2242    mCount = 0;
2243}
2244
2245void LayerRotMap::clear() {
2246    RotMgr::getInstance()->markUnusedTop(mCount);
2247    reset();
2248}
2249
2250void LayerRotMap::setReleaseFd(const int& fence) {
2251    for(uint32_t i = 0; i < mCount; i++) {
2252        mRot[i]->setReleaseFd(dup(fence));
2253    }
2254}
2255
2256void resetROI(hwc_context_t *ctx, const int dpy) {
2257    const int fbXRes = (int)ctx->dpyAttr[dpy].xres;
2258    const int fbYRes = (int)ctx->dpyAttr[dpy].yres;
2259    if(isDisplaySplit(ctx, dpy)) {
2260        const int lSplit = getLeftSplit(ctx, dpy);
2261        ctx->listStats[dpy].lRoi = (struct hwc_rect){0, 0, lSplit, fbYRes};
2262        ctx->listStats[dpy].rRoi = (struct hwc_rect){lSplit, 0, fbXRes, fbYRes};
2263    } else  {
2264        ctx->listStats[dpy].lRoi = (struct hwc_rect){0, 0,fbXRes, fbYRes};
2265        ctx->listStats[dpy].rRoi = (struct hwc_rect){0, 0, 0, 0};
2266    }
2267}
2268
2269hwc_rect_t getSanitizeROI(struct hwc_rect roi, hwc_rect boundary)
2270{
2271   if(!isValidRect(roi))
2272      return roi;
2273
2274   struct hwc_rect t_roi = roi;
2275
2276   const int LEFT_ALIGN = qdutils::MDPVersion::getInstance().getLeftAlign();
2277   const int WIDTH_ALIGN = qdutils::MDPVersion::getInstance().getWidthAlign();
2278   const int TOP_ALIGN = qdutils::MDPVersion::getInstance().getTopAlign();
2279   const int HEIGHT_ALIGN = qdutils::MDPVersion::getInstance().getHeightAlign();
2280   const int MIN_WIDTH = qdutils::MDPVersion::getInstance().getMinROIWidth();
2281   const int MIN_HEIGHT = qdutils::MDPVersion::getInstance().getMinROIHeight();
2282
2283   /* Align to minimum width recommended by the panel */
2284   if((t_roi.right - t_roi.left) < MIN_WIDTH) {
2285       if((t_roi.left + MIN_WIDTH) > boundary.right)
2286           t_roi.left = t_roi.right - MIN_WIDTH;
2287       else
2288           t_roi.right = t_roi.left + MIN_WIDTH;
2289   }
2290
2291  /* Align to minimum height recommended by the panel */
2292   if((t_roi.bottom - t_roi.top) < MIN_HEIGHT) {
2293       if((t_roi.top + MIN_HEIGHT) > boundary.bottom)
2294           t_roi.top = t_roi.bottom - MIN_HEIGHT;
2295       else
2296           t_roi.bottom = t_roi.top + MIN_HEIGHT;
2297   }
2298
2299   /* Align left and width to meet panel restrictions */
2300   if(LEFT_ALIGN)
2301       t_roi.left = t_roi.left - (t_roi.left % LEFT_ALIGN);
2302
2303   if(WIDTH_ALIGN) {
2304       int width = t_roi.right - t_roi.left;
2305       width = WIDTH_ALIGN * ((width + (WIDTH_ALIGN - 1)) / WIDTH_ALIGN);
2306       t_roi.right = t_roi.left + width;
2307
2308       if(t_roi.right > boundary.right) {
2309           t_roi.right = boundary.right;
2310           t_roi.left = t_roi.right - width;
2311
2312           if(LEFT_ALIGN)
2313               t_roi.left = t_roi.left - (t_roi.left % LEFT_ALIGN);
2314       }
2315   }
2316
2317
2318   /* Align top and height to meet panel restrictions */
2319   if(TOP_ALIGN)
2320       t_roi.top = t_roi.top - (t_roi.top % TOP_ALIGN);
2321
2322   if(HEIGHT_ALIGN) {
2323       int height = t_roi.bottom - t_roi.top;
2324       height = HEIGHT_ALIGN *  ((height + (HEIGHT_ALIGN - 1)) / HEIGHT_ALIGN);
2325       t_roi.bottom = t_roi.top  + height;
2326
2327       if(t_roi.bottom > boundary.bottom) {
2328           t_roi.bottom = boundary.bottom;
2329           t_roi.top = t_roi.bottom - height;
2330
2331           if(TOP_ALIGN)
2332               t_roi.top = t_roi.top - (t_roi.top % TOP_ALIGN);
2333       }
2334   }
2335
2336
2337   return t_roi;
2338}
2339
2340};//namespace qhwc
2341